gpt4 book ai didi

r - 如何使用 dplyr 创建总频率表

转载 作者:行者123 更新时间:2023-12-02 20:16:02 24 4
gpt4 key购买 nike

使用 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 管道上的 mutate 仅按第一个分组变量分组(或者为什么它根本分组的原因 - 我的想法是应该在 >summarise() 数据集)将不胜感激。

total 列应指示总共有 8 个案例(即 summarise() 中先前结果的 sum(n) > 应该= 8)。

最佳答案

每次汇总后,其中一个分组元素将被删除,即按该顺序的最后一组。在总结之后我们需要取消分组

dat1 %>% 
group_by(color, type) %>%
summarise(n = n()) %>%
ungroup %>%
mutate(total = sum(n), rel.freq = n / total)
# A tibble: 4 x 5
# color type n total rel.freq
# <fct> <fct> <int> <int> <dbl>
#1 green big 2 8 0.25
#2 green small 2 8 0.25
#3 red big 2 8 0.25
#4 red small 2 8 0.25

关于r - 如何使用 dplyr 创建总频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52370511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com