【问题标题】:logical value count with summarise r使用汇总 r 进行逻辑值计数
【发布时间】:2019-02-16 01:44:49
【问题描述】:

在数据框中,我有一列包含 Y 和 N 值。这个数据框也有一个 id 列。我想创建两列,一列包含总 Y 计数,另一列包含每个 ID 的总 N 计数。我尝试使用 dplyr 汇总函数执行此过程

 group_by(id) %>%
 summarise(total_not = count(column_y_e_n == "N"),
           total_yes = count(column_y_e_n == "Y")

但对错误信息表示反对

summarise_impl(.data, dots) 中的错误

有什么建议吗?

【问题讨论】:

  • 您可能需要使用sum 而不是count
  • 你错过了)

标签: r dplyr grouping summarization


【解决方案1】:

我把count函数换成sum函数,成功了。

 group_by(id) %>%
 summarise(total_not = sum(column_y_e_n == "N"),
           total_yes = sum(column_y_e_n == "Y")

【讨论】:

    【解决方案2】:

    Harro 的原始答案略有不同:

    library(tidyr)
    
    dfr <- data.frame(
      id =  c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3),
      bool = c("Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "Y", "N", "N", "N")
    )
    
    dfrSummary <- dfr %>% 
      group_by(
        id, bool
        ) %>% 
      summarize(
        count = n()
        ) %>% 
      spread(
        key = bool, 
        value = count, 
        fill = 0
        )
    
    

    【讨论】:

      【解决方案3】:

      我会使用 group_by 和 tally() 来解决这个问题。或者你可以跳过中间步骤,直接使用count。

      library(tidyverse)
      
      ##Fake data
      df <- tibble(
          id = rep(1:20,each = 10),
          column_y_e_n = sapply(1:200, function(i)sample(c("Y", "N"),1))
      )
      
      ##group_by() + tally()
      df_2 <- df %>%
          group_by(id, column_y_e_n) %>%
          tally() %>%
          spread(column_y_e_n, n) %>%
          magrittr::set_colnames(c("id", "total_not", "total_yes"))
      
      
      df_2
      
      #direct method
      df_3 <- df %>%
          count(id, column_y_e_n) %>%
          spread(column_y_e_n, n) %>%
          magrittr::set_colnames(c("id", "total_not", "total_yes"))
      
      df_3
      

      最后的管道传播结果列并格式化列名。

      【讨论】:

        【解决方案4】:

        我通常想在 tidyverse 中做所有事情。但在这种情况下,基本 R 解决方案似乎是合适的:

        dfr <- data.frame(
          id =  c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3),
          column_y_e_n = c("Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "Y", "N", "N", "N")
        )
        
        table(dfr)
        

        给你:

           column_y_e_n
        id  N Y
          1 1 4
          2 3 2
          3 3 0
        

        【讨论】:

          猜你喜欢
          • 2015-01-04
          • 2014-06-26
          • 1970-01-01
          • 2017-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多