Structure R Dataframe from Long to Wide

前端 未结 1 1200
一个人的身影
一个人的身影 2021-01-07 05:59

I have a dateframe as such:

long <- data.frame(subj = c(1,1,2,2,2), code = c(\"a\", \"b\", \"a\", \"d\", \"e\"))

   subj code
 1    1    a
 2    1    b
          


        
相关标签:
1条回答
  • 2021-01-07 06:28

    We create a sequence column for the grouping column 'subj' and then do dcast. We can use dcast from data.table. Convert the 'data.frame' to 'data.table' (setDT(long)), grouped by 'subj', create the sequence column 'new' and reshape from 'long' to 'wide' with dcast.

    library(data.table)#v1.9.6+
    setDT(long)[, new:=paste('code', 1:.N, sep='.'), by = subj]
    dcast(long, subj~new, value.var='code')
    

    Or this can be done with spread from tidyr after creating the sequence column using dplyr methods

    library(dplyr)
    library(tidyr)
    long %>% 
        group_by(subj) %>% 
        mutate(new=paste('code', row_number(), sep='.')) %>% 
        spread(new, code)
    
    0 讨论(0)
提交回复
热议问题