Search code examples
rdata.tablereshape2

dcast from wide to long


this ought to be easy but I cant find the correct way to do it.

jk <- data.frame(j=c("a","b","a","b"),val=c(1,3,2,1))

I´d like dcast to return two columns a and b with {1,2} and {3,1} respectively.


Solution

  • In base R, we can use unstack

    unstack(jk, val ~ j)
    

    -output

    #  a b
    #1 1 3
    #2 2 1
    

    If we use dcast, create a sequence column because there are duplicates for 'j'

    library(data.table)
    dcast(setDT(jk), rowid(j) ~ j, value.var = 'val')[, j := NULL][]
    

    -output

    #  a b
    #1: 1 3
    #2: 2 1