Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert dataframe of two characters and a value into a trinagle matrix in R

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading