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

Transform dataframe to binary dataframe in R

I have a dataframe such as

Groups Names
G1     SP1
G1     SP2
G1     SP3
G2     SP1
G2     SP4
G3     SP2
G3     SP1 

And I would like to transform it as :

  Names G1 G2 G3
  SP1   1  1  1
  SP2   1  0  1  
  SP3   1  0  0 
  SP4   0  1  0

Where in columns are the Groups
and within cell 1 = present and 0 = absent

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

Here is the dput format

structure(list(Groups = c("G1", "G1", "G1", "G2", "G2", "G3", 
"G3"), Names = c("SP1", "SP2", "SP3", "SP1", "SP4", "SP2", "SP1"
)), class = "data.frame", row.names = c(NA, -7L))

>Solution :

Use table:

table(df$Names, df$Groups)
     
      G1 G2 G3
  SP1  1  1  1
  SP2  1  0  1
  SP3  1  0  0
  SP4  0  1  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