简体   繁体   中英

Unconventional data frame reshaping using dcast

I want to convert table dt:

Who T Res
Pam 2 B
Pam 3 E
Pam 5 F
Bob 2 B
Bob 5 C

into

Who T1 Res1 T2 Res2 T3 Res3
Pam  2  B    3  E    5  F 
Bob  2  B    5  C   NA  NA

using dcast or other function/s from data.table.

I have tried things such as dcast(dt, Who ~ T + Res) but got just undesired outputs.

You can use -

library(data.table)

setDT(dt)
dcast(dt, Who ~ rowid(Who), value.var = c('T', 'Res'))

#   Who T_1 T_2 T_3 Res_1 Res_2 Res_3
#1: Bob   2   5  NA     B     C  <NA>
#2: Pam   2   3   5     B     E     F

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM