Search code examples
rdatatable

Converting n values of a column into n rows


data.table(A=c("a","a","b","b","c","c"),
           B=c(3,2,4,7,12,13))->dt

Desired output:

A V1 V2
a 3  2
b 4  7
c 12 13

I want to preserve the order of column B while transforming them into row values. Any help would be much appreciated.

Dcast command wasn't of any help. I further tried this:

as.data.frame(matrix(dt$B[dt$B!=""], ncol=2, byrow=TRUE)) -> d1

Although it did do the trick, but I am not sure of using it with big datasets as it might upset the order of column B and A.


Solution

  • I was able to get the desired output with dcast():

    dcast(dt, A ~ paste0("V", rowid(A)) , value.var = "B")
    #> Key: <A>
    #>         A    V1    V2
    #>    <char> <num> <num>
    #> 1:      a     3     2
    #> 2:      b     4     7
    #> 3:      c    12    13