2

I have a dataframe which has unique ids and other columns like this:

df = data.frame(id = c('id1', 'id2', 'id3'), 
                col_1 = c(0,1,0), 
                col_2 = c(1,0,0), 
                col_3 = c(1,1,NA), 
                col_4 = c(1,NA,NA))

How is it possible to melt the dataframe aiming to have 2 columns one with the id which will be repeated based on the number of columns and the second column will contain the value from the other columns.

Example of expected output:

df = data.frame(id = c('id1', 'id1', 'id1', 'id1', 'id2', 'id2', 'id2', 'id2', 'id3', 'id3', 'id3', 'id3'), 
                col_1 = c(0,1,1,1,1,0,1,NA,0,0,NA,NA))
alistaire
  • 42,459
  • 4
  • 77
  • 117
PitterJe
  • 216
  • 2
  • 12

1 Answers1

1

Try:

library(reshape2)
df = data.frame(id=c('id1', 'id2', 'id3'),col_1 = c(0,1,0),col_2 = c(1,0,0),col_3 = c(1,1,NA),col_4 = c(1,NA,NA))
x <- melt(df, id.vars = "id")
x[order(x$id),c(1,3)]
Pierre
  • 671
  • 8
  • 25
  • Thank you it works. in the `x[order(x$id),c(1,3)]` the c(1,3) refer to the number of rows of the input dataframe? – PitterJe Nov 16 '17 at 13:33
  • Great! When working with matrices in R, the first value between the brackets refers to row and the second to column (x[row, column]). I.e. c(1,3) slice out column 1 and 3 from the matrix (and order(x$id) just sorts the rows) @PitterJe – Pierre Nov 16 '17 at 14:02