【问题标题】:collapsing rows based on two other colums in R基于R中的其他两列折叠行
【发布时间】:2021-07-10 10:32:27
【问题描述】:

在我的论文中,我有一个包含变量 yearagegroupcount 的数据框。 对于每个year,我想将agegroups'0-4'、'5-9'和'10-14'折叠成'0-14',将count相加。

我想要这个:

  year agegroup count
1 1990      0-4     1
2 1990      5-9     1
3 1990    10-14     1
4 1990    15-19     7
5 1991      0-4     1
6 1991      5-9     3
7 1991    10-14     1
8 1991    15-19     7

变成这样:

  year agegroup count
1 1990     0-14     3
2 1990    15-19     7
3 1991     0-14     5
4 1991    15-19     7

我不知道如何巧妙地做到这一点,希望有任何建议!

【问题讨论】:

    标签: r dataframe statistics


    【解决方案1】:
    df$agegroup2=gsub("0-4|5-9|10-14","0-14",df$agegroup)
    
    aggregate(count~year+agegroup2,df,sum)
    
      year agegroup2 count
    1 1990      0-14     3
    2 1991      0-14     5
    3 1990     15-19     7
    4 1991     15-19     7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多