【发布时间】:2018-09-17 14:54:57
【问题描述】:
使用dplyr 创建总相对频率表并按两个变量分组时,我得到了一个意外的结果。这是一个例子:
set.seed(1234)
dat1 = data.frame(
color = c(c(rep("red", 4), rep("green", 4))),
type = c(c(rep(c(
"big", "small"
), 4))),
value = sample(1:6, 8, replace = T)
)
dat1 %>% group_by(color, type) %>% summarise(n = n()) %>%
mutate(total = sum(n), rel.freq = n / total)
这是前面代码的结果:
# A tibble: 4 x 5
# Groups: color [2]
color type n total rel.freq
<fct> <fct> <int> <int> <dbl>
1 green big 2 4 0.500
2 green small 2 4 0.500
3 red big 2 4 0.500
4 red small 2 4 0.500
但我希望这样:
# A tibble: 4 x 5
# Groups: color [2]
color type n total rel.freq
<fct> <fct> <int> <int> <dbl>
1 green big 2 8 0.250
2 green small 2 8 0.250
3 red big 2 8 0.250
4 red small 2 8 0.250
任何深入了解为什么下面的dplyr 管道上的变异仅按第一个分组变量分组(或者为什么它根本分组 - 我的想法是应该在 summarise() 数据集上工作)不胜感激。
total 列应指示总共有 8 个案例(即,summarise() 中先前结果的sum(n) 应为= 8)。
【问题讨论】: