tidyr::spread() with multiple keys and values

后端 未结 3 1779
耶瑟儿~
耶瑟儿~ 2020-12-21 10:37

I assume this has been asked multiple times but I couldn\'t find the proper words to find a workable solution.

How can I spread() a data frame based on

3条回答
  •  我在风中等你
    2020-12-21 11:05

    Reshaping with multiple value variables can best be done with dcast from data.table or reshape from base R.

    library(data.table)
    out <- dcast(setDT(df), id ~ paste0("time", time), value.var = c("x", "y"), sep = "")
    out
    #    id     xtime1     xtime2      xtime3      ytime1      ytime2      ytime3
    # 1:  1  0.4334921 -0.5205570 -1.44364515  0.49288757 -1.26955148 -0.83344256
    # 2:  2  0.4785870  0.9261711  0.68173681  1.24639813  0.91805332  0.34346260
    # 3:  3 -1.2067665  1.7309593  0.04923993  1.28184341 -0.69435556  0.01609261
    # 4:  4  0.5240518  0.7481787  0.07966677 -1.36408357  1.72636849 -0.45827205
    # 5:  5  0.3733316 -0.3689391 -0.11879819 -0.03276689  0.91824437  2.18084692
    # 6:  6  0.2363018 -0.2358572  0.73389984 -1.10946940 -1.05379502 -0.82691626
    # 7:  7 -1.4979165  0.9026397  0.84666801  1.02138768 -0.01072588  0.08925716
    # 8:  8  0.3428946 -0.2235349 -1.21684977  0.40549497  0.68937085 -0.15793111
    # 9:  9 -1.1304688 -0.3901419 -0.10722222 -0.54206830  0.34134397  0.48504564
    #10: 10 -0.5275251 -1.1328937 -0.68059800  1.38790593  0.93199593 -1.77498807
    

    Using reshape we could do

    # setDF(df) # in case df is a data.table now
    reshape(df, idvar = "id", timevar = "time", direction = "wide")
    

提交回复
热议问题