How to reshape tabular data to one row per group

后端 未结 5 1329
轻奢々
轻奢々 2020-12-21 23:57

I am an R (and coding novice) and I am looking for a way to reconfigure Table A show below into Table B.

Table A:

type   x1  x2  x3  
A      4   6            


        
5条回答
  •  长情又很酷
    2020-12-22 00:27

    A bit late to the party, but this can also be done quite easily with the dcast function of the data.table package because you can use multiple value.var's in it:

    library(data.table)
    
    dcast(setDT(d), type ~ rowid(type), value.var = c('x1','x2','x3'), sep = '')
    

    which gives:

       type x11 x12 x13 x21 x22 x23 x31 x32 x33
    1:    A   4   7   9   6   4   6   9   1   2
    2:    B   1   2  NA   3   7  NA   8   9  NA
    

    You can also do this in base R with:

    d$num <- ave(d$x1, d$type, FUN = seq_along)
    reshape(d, idvar = 'type', direction = 'wide', timevar = 'num', sep = '')
    

提交回复
热议问题