From long to wide data with multiple columns

后端 未结 3 1357
渐次进展
渐次进展 2020-12-06 19:19

Suggestions for how to smoothly get from foo to foo2 (preferably with tidyr or reshape2 packages)?

This is kind of like this question, but not exactly I think, becau

相关标签:
3条回答
  • 2020-12-06 19:38

    You can use data.table instead of reshape2, because its dcast() function accepts several variables, and is faster too:

    require(data.table)
    setDT(foo)
    dcast(foo,group+num_users~times,value.var=c("action_rate","action_rate_c95"))
    
       group num_users action_rate_after action_rate_before action_rate_c95_after action_rate_c95_before
    1:     a       100              0.15                0.1            0.06962893             0.05850000
    2:     b       200              0.18                0.2            0.05297400             0.05515433
    3:     c       300              0.35                0.3            0.05369881             0.05159215
    
    0 讨论(0)
  • 2020-12-06 19:43

    Here is a base R option with reshape

    reshape(foo, idvar=c("group", "num_users"), timevar="times", direction="wide")
    #  group num_users action_rate.before action_rate_c95.before action_rate.after
    #1     a       100                0.1             0.05850000              0.15
    #3     b       200                0.2             0.05515433              0.18
    #5     c       300                0.3             0.05159215              0.35
    #  action_rate_c95.after
    #1            0.06962893
    #3            0.05297400
    #5            0.05369881
    
    0 讨论(0)
  • 2020-12-06 19:46

    Here's another alternative using tidyr:

    library(tidyr)
    foo %>%
      gather(key, value, -group, -times, -num_users) %>%
      unite(col, key, times) %>%
      spread(col, value)
    

    Which gives:

    #  group num_users action_rate_after action_rate_before action_rate_c95_after
    #1     a       100              0.15                0.1            0.06962893
    #2     b       200              0.18                0.2            0.05297400
    #3     c       300              0.35                0.3            0.05369881
    #  action_rate_c95_before
    #1             0.05850000
    #2             0.05515433
    #3             0.05159215
    
    0 讨论(0)
提交回复
热议问题