【问题标题】:How can I save grouped counts across factor levels into a new variable with dplyr?如何使用 dplyr 将跨因子级别的分组计数保存到新变量中?
【发布时间】:2021-11-22 01:11:59
【问题描述】:

我尝试将各种因素水平的分组计数保存到一个新变量中:

假设我的数据如下所示:


a <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4)
b <- c("acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con","acc", "rej", "con", "acc", "rej")

df <- data.frame(a,b) 

生成的数据框应如下所示:


a <- c(1,2,3,4)
number_acc <- c(2,2,1,2)
number_rej <- c(2,1,2,2)
number_con <- c(1,2,2,1)

我尝试通过以下方式解决问题:


df2 <- df %>%
  group_by(a) %>% 
  mutate(number_acc = count(b == 'acc'), 
         number_rej = count(b == 'rej'),
         number_con = count(b == 'con'))

但是,我收到一条错误消息,指出方法“count”不能应用于“logical”类的对象。

感谢您的帮助!

【问题讨论】:

  • 尝试使用 sum,而不是 count。或者只是as.data.frame.matrix(table(df))
  • 你需要总结,而不是变异。
  • 可能重复,相关帖子:stackoverflow.com/q/40266062/680068
  • 非常感谢。当我使用 sum 而不是 count 时,一个小问题仍然存在:我为变量 a 和 b 的每个组合得到一行,但我希望在新数据帧中只有一次变量 a。
  • 完美搭配摘要!再次感谢你! :-)

标签: r dplyr group-by count


【解决方案1】:

使用 janitor 包中的 tabyl 函数:

您的数据:

a <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4)
b <- c("acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con", "acc", "rej", "con","acc", "rej", "con", "acc", "rej")

df <- data.frame(a,b)

按计数汇总分组:

library(janitor)
data_summary <- tabyl(df, a, b)
data_summary

# a acc con rej
# 1   2   1   2
# 2   2   2   1
# 3   1   2   2
# 4   2   1   2

【讨论】:

    【解决方案2】:

    要使现有代码正常工作,我们需要 summarise 而不是 mutate,以及 sum 而不是 count em>:

    df %>%
      group_by(a) %>% 
      summarise(number_acc = sum(b == 'acc'), 
                number_rej = sum(b == 'rej'),
                number_con = sum(b == 'con'))
    
    # # A tibble: 4 x 4
    #       a number_acc number_rej number_con
    #   <dbl>      <int>      <int>      <int>
    # 1     1          2          2          1
    # 2     2          2          1          2
    # 3     3          1          2          2
    # 4     4          2          2          1
    

    但是有更好的方法可以做到这一点,例如查看答案:

    【讨论】:

      【解决方案3】:

      这是另一种方法: 我们可以在count 之后使用pivot_widernames_glue

      library(tidyr)
      library(dplyr)
      
      df %>% 
        count(a,b) %>% 
        pivot_wider(
          names_from = b,
          values_from = n,
          names_glue = "{b}_{'number'}"
        )
      
            a acc_number con_number rej_number
        <dbl>      <int>      <int>      <int>
      1     1          2          1          2
      2     2          2          2          1
      3     3          1          2          2
      4     4          2          1          2
      

      【讨论】:

      • 完美!我只是问自己如何使用计数来做到这一点。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      相关资源
      最近更新 更多