Home > Software engineering >  Convert dataframe of two characters and a value into a trinagle matrix in R
Convert dataframe of two characters and a value into a trinagle matrix in R

Time:04-13

I have a dataframe/tibble like this:

d <- data.frame(groupa = c("A", "A", "A", "B", "B", "C"), 
                groupb = c("A", "B", "C", "B", "C", "C"), 
                val = c(0, 1.1, 2.0, 0, 2.5, 0))

>d
  groupa groupb val
1      A      A 0.0
2      A      B 1.1
3      A      C 2.0
4      B      B 0.0
5      B      C 2.5
6      C      C 0.0

And I would like to turn it into a pairwise matrix like this:

       A   B   C
     A 0  
     B 1.1 0   0 
     C 2.0 2.5 0

I can't figure out any way to make each value of groupa into a column, groupb into a row, and the value as the meeting point in the matrix. A tidyverse method would be greatly appreciated!

CodePudding user response:

We can use xtabs from base R

xtabs(val ~ groupb   groupa, d)

-output

    groupa
groupb   A   B   C
     A 0.0 0.0 0.0
     B 1.1 0.0 0.0
     C 2.0 2.5 0.0
  • Related