【问题标题】:How to group by ID and expand dataframe by another column如何按 ID 分组并按另一列扩展数据框
【发布时间】:2019-04-25 14:31:37
【问题描述】:

我想扩展我的数据集,以便每个 ID 有一行,并且“步骤”列中的每个值都有自己的行。

我尝试了 group_by 并在 dplyr 中传播,但没有达到我想要的结果。

我的数据集是这样的

df = data.frame(id = c(1,1,2,2,3,3,3,4,4,4,4,4), 
       points = c(0,1,0,1,0,1,2,0,1,2,3,4), 
       step = c(0, 0, 0, 0, 0.0000, -1.9701, -1.6758, 0.0000, -2.5414,-2.5397,1.1516,  3.9296))

   id points    step
1   1      0  0.0000
2   1      1  0.0000
3   2      0  0.0000
4   2      1  0.0000
5   3      0  0.0000
6   3      1 -1.9701
7   3      2 -1.6758
8   4      0  0.0000
9   4      1 -2.5414
10  4      2 -2.5397
11  4      3  1.1516
12  4      4  3.9296

我希望最终结果如下所示,其中原始数据集中的“点”列指示最终数据集中的列名:

 id step0   step1   step2  step3  step4
1  1     0  0.0000      NA     NA     NA
2  2     0  0.0000      NA     NA     NA
3  3     0 -1.9701 -1.6758     NA     NA
4  4     0 -2.5414 -2.5397 1.1516 3.9296

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    我们可以使用spread

    library(tidyverse)
    df %>% 
        mutate(points = str_c("step", points)) %>%
        spread(points, step)
    #  id step0   step1   step2  step3  step4
    #1  1     0  0.0000      NA     NA     NA
    #2  2     0  0.0000      NA     NA     NA
    #3  3     0 -1.9701 -1.6758     NA     NA
    #4  4     0 -2.5414 -2.5397 1.1516 3.9296
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2019-09-18
      • 2021-08-26
      相关资源
      最近更新 更多