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

How to transform a dataframe into a matrix of combinations

I have a data frame of one row that contains the results of an equation of two variables (let’s call them X and Y; for simplicity, the equation is a sum). I need to transform that dataframe into a matrix where I can see the combinations of those variables. This is a reproducible example:

x1_y1 <- 2 #Here x = 1, y = 1
x1_y2 <- 3 #Here x = 1, y = 2
x2_y1 <- 3 #Here x = 2, y = 1
x2_y2 <- 4 #Here x = 2, y = 2

df <- data.frame(x1_y1, x1_y2, x2_y1, x2_y2)

I would like the output to be something like this:

enter image description here

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

Does anybody know how to achieve this? Thanks in advance!

>Solution :

A tapply attempt after extracting the name components via strcapture:

tapply(unlist(df), strcapture("(.+)_(.+)", names(df), proto=list(x="",y="")), I)
#    y
#x    y1 y2
#  x1  2  3
#  x2  3  4
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