【问题标题】:Summarizing by subgroup percentage in R按 R 中的子组百分比汇总
【发布时间】:2015-01-23 22:00:39
【问题描述】:

我有一个这样的数据集:

df = data.frame(group = c(rep('A',4), rep('B',3)),
                subgroup = c('a', 'b', 'c', 'd', 'a', 'b', 'c'),
                value = c(1,4,2,1,1,2,3))


group | subgroup | value
------------------------
  A   |    a     |  1
  A   |    b     |  4
  A   |    c     |  2
  A   |    d     |  1
  B   |    a     |  1
  B   |    b     |  2
  B   |    c     |  3

我想要的是获得每个组中每个子组的值的百分比,即输出应该是:

group | subgroup | percent
------------------------
  A   |    a     |  0.125
  A   |    b     |  0.500
  A   |    c     |  0.250
  A   |    d     |  0.125
  B   |    a     |  0.167
  B   |    b     |  0.333
  B   |    c     |  0.500

以 A 组为例,A 子组:值为 1,整个 A 组的总和为 8(a=1,b=4,c=2,d=1) - 因此 1/8 = 0.125

到目前为止,我只找到了相当简单的聚合,例如 this,但我不知道如何执行“除以子组内的总和”部分。

【问题讨论】:

    标签: r aggregate percentage


    【解决方案1】:

    根据您的评论,如果子组是唯一的,您可以这样做

    library(dplyr)
    group_by(df, group) %>% mutate(percent = value/sum(value))
    #   group subgroup value   percent
    # 1     A        a     1 0.1250000
    # 2     A        b     4 0.5000000
    # 3     A        c     2 0.2500000
    # 4     A        d     1 0.1250000
    # 5     B        a     1 0.1666667
    # 6     B        b     2 0.3333333
    # 7     B        c     3 0.5000000
    

    或者要删除value列并同时添加percent列,使用transmute

    group_by(df, group) %>% transmute(subgroup, percent = value/sum(value))
    #   group subgroup   percent
    # 1     A        a 0.1250000
    # 2     A        b 0.5000000
    # 3     A        c 0.2500000
    # 4     A        d 0.1250000
    # 5     B        a 0.1666667
    # 6     B        b 0.3333333
    # 7     B        c 0.5000000
    

    【讨论】:

      【解决方案2】:

      我们可以使用prop.table 来计算百分比/比率。

      基础R:

      transform(df, percent = ave(value, group, FUN = prop.table))
      
      #  group subgroup value percent
      #1     A        a     1   0.125
      #2     A        b     4   0.500
      #3     A        c     2   0.250
      #4     A        d     1   0.125
      #5     B        a     1   0.167
      #6     B        b     2   0.333
      #7     B        c     3   0.500
      

      dplyr

      library(dplyr)
      df %>% group_by(group) %>% mutate(percent = prop.table(value))
      

      data.table

      library(data.table)
      setDT(df)[, percent := prop.table(value), group]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-15
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        相关资源
        最近更新 更多