Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading