【问题标题】:How to create total frequency table using dplyr如何使用 dplyr 创建总频率表
【发布时间】: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)。

【问题讨论】:

    标签: r group-by dplyr


    【解决方案1】:

    在每个summarise 之后,将删除一个分组元素,即按该顺序的最后一组。我们需要在summarise之后ungroup

    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
    

    【讨论】:

    • 就是这样 - 我有 4 分钟的时间去接受这个答案,但它做到了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2022-08-09
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多