r - Convert a dataframe to presence absence matrix -


i have table has unequal number of element in string format

file1  b  c file2  b  d file3 e  f 

i want convert format follows

        b c d e f file1   1 1 1 0 0 0  file2   1 1 0 1 0 0 file3   0 0 0 0 1 1 

i tried using reshape2 not successful.

sample data:

mydata <- structure(list(v1 = c("file1", "file2", "file3"),                           v2 = c("a", "a", "e"), v3 = c("b", "b", "f"),                           v4 = c("c", "d", "")),                     .names = c("v1", "v2", "v3", "v4"),                     class = "data.frame", row.names = c(na, -3l)) 

one possibility:

library(reshape2) df2 <- melt(df, id.var = "v1") with(df2, table(v1, value))  #         value # v1      b c d e f #   file1 1 1 1 0 0 0 #   file2 1 1 0 1 0 0 #   file3 0 0 0 0 1 1 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -