计算子组内值的比例

Calculate proportion of values within subgroup

我正在尝试通过 cond 计算 valuestype 中的比例,但我无法先通过 cond 计算类型的总和。有人有建议吗?谢谢!

玩具数据集

cond  type  value
x      A     2
x      A     4
x      B     1
y      C     7
y      D     2
y      D     3
y      E     5
...    ...   ...

期望的输出:
例如,A 的比例为 6/(6+1) = .857

cond type sum  proportion
x     A    6   .857
x     B    1   .143
y     C    7   .411
y     D    5   .294
y     E    5   .294
...   ...   ...

我们可以在 summarise 中按 sum 做一个小组。默认情况下,在 summarise 之后删除最后一个分组,因此,使用 mutate 将 'Sum' 除以 'Sum' 列的 sum

library(dplyr)
df1 %>%
    group_by(cond, type) %>%
    summarise(Sum = sum(value)) %>%
    mutate(proportion = Sum/sum(Sum))
# A tibble: 5 x 4
# Groups:   cond [2]
#  cond  type    Sum proportion
#  <chr> <chr> <int>      <dbl>
#1 x     A         6      0.857
#2 x     B         1      0.143
#3 y     C         7      0.412
#4 y     D         5      0.294
#5 y     E         5      0.294

或使用 base R

中的 prop.table
prop.table(xtabs(value ~ cond + type, df1), 1)

数据

df1 <- structure(list(cond = c("x", "x", "x", "y", "y", "y", "y"), type = c("A", 
"A", "B", "C", "D", "D", "E"), value = c(2L, 4L, 1L, 7L, 2L, 
3L, 5L)), class = "data.frame", row.names = c(NA, -7L))

另一个基础 R 选项是:

transform(aggregate(value~.,df,sum), prop = ave(value, cond,FUN = prop.table))

  cond type value      prop
1    x    A     6 0.8571429
2    x    B     1 0.1428571
3    y    C     7 0.4117647
4    y    D     5 0.2941176
5    y    E     5 0.2941176

为了完整起见,这里有一个 data.table 解决方案:

library(data.table)
setDT(df)[, sum(value), .(cond, type)][, proportion := V1/sum(V1), cond][]
#OR using prop.table
#setDT(df)[, sum(value), .(cond, type)][, proportion := prop.table(V1), cond][]

#   cond type V1 proportion
#1:    x    A  6  0.8571429
#2:    x    B  1  0.1428571
#3:    y    C  7  0.4117647
#4:    y    D  5  0.2941176
#5:    y    E  5  0.2941176