[Solved] melting data.frame in R


Here’s a one-liner, base solution:

out <- t(apply(mydf, 2, function(x) row.names(mydf)[which(as.logical(x))]))

The result is a matrix:

> out
      [,1]    [,2]   
name1 "word1" "word3"
name2 "word2" "word3"
name3 "word1" "word2"

which is easily made into a dataframe:

> as.data.frame(out)
         V1    V2
name1 word1 word3
name2 word2 word3
name3 word1 word2

Here’s your data as I read it in:

mydf <- read.table(text="      name1    name2    name3
word1  1         0        1
word2  0         1        1
word3  1         1        0", header=TRUE)

0

solved melting data.frame in R