-3

I have a dataframe in R in the format below

      name1    name2    name3
word1  1         0        1
word2  0         1        1
word3  1         1        0

I would like to melt this dataframe into:

name1 |word1|word3
name2 |word2|word3
name3 |word1|word2
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user1375640
  • 141
  • 3
  • 12
  • 2
    [A reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) is an essential question element. Demonstrated effort is nice, too. – Thomas May 20 '14 at 19:48
  • 2
    You also need to describe how the result should be derived from the input. I have no idea, why it has 2 columns with "words". – Roland May 20 '14 at 19:52
  • So basically, in the dataframe, "words" are the first column, the "names" are for columns 2,3,4. Usually the function melt in the reshape2 package will melt this dataframe into 3 columns. But, what I am looking for is to have the columnames "names" in the first column, and all the other "words" one in each column according to their relationship with the names. – user1375640 May 20 '14 at 20:31

1 Answers1

1

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)
Thomas
  • 43,637
  • 12
  • 109
  • 140