rreshape2

Reshape wide to long, preserving ID variable from rownames


I am trying to get the following data into long format in R:

testdata <- data.frame(rnorm(10),rnorm(10),rnorm(10))
rownames(testdata) <- paste0("ID",1:10) # Ids
colnames(testdata) <- c(2001,2002,2003) # Years
testdata

So the columns = time, the rows = IDs. Should not be too hard, but in all the examples I found it was the other way around. How can this be done in datatable or reshape or in any other of the popular dataframe packages? Thanks for any hints. I know one way by transposing my data, but this seems to be a rather inefficient way for this purpose.


Solution

  • Just to turn akrun's comment into a complete answer:

    library(data.table)
    melt(setDT(testdata, keep.rownames = TRUE), "rn")
    
          rn variable       value
     1:  ID1     2001 -0.25265860
     2:  ID2     2001  0.50538399
     3:  ID3     2001  0.68216394
     4:  ID4     2001  0.62203871
     5:  ID5     2001  0.59297019
     6:  ID6     2001  0.69383842
     7:  ID7     2001  1.77900432
     8:  ID8     2001 -1.69010623
     9:  ID9     2001 -2.17762905
    10: ID10     2001  0.61463127
    11:  ID1     2002  0.42120060
    12:  ID2     2002 -0.16148732
    ...