【问题标题】:Conditional count in data frame数据框中的条件计数
【发布时间】:2017-06-08 19:14:19
【问题描述】:

我有一个包含三列的数据框 (df),如下所示:

结构:

id id1 age
A1 a1  32
A1 a2  45
A1 a3  45
A1 a4  12
A2 b1  15
A2 b5  34
A2 b64 17

预期输出:

id count count1
A1 4     1
A2 3     2

逻辑:

  • “count”列是“id”重复的次数
  • “count1”列是年龄小于 21 的行数

当前代码:

library(dplyr)
df_summarized <- df %>% 
                     group_by(id) >%> 
                     summarise(count = n(),count1 = count(age<21)) 

问题:

Error: no applicable method for 'group_by_' applied to an object of class "logical"

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    我们需要做sum

    df %>% 
        group_by(id) %>% 
        summarise(count = n(),count1 = sum(age < 21))
    # A tibble: 2 × 3
    #     id count count1
    #  <chr> <int>  <int>
    #1    A1     4      1
    #2    A2     3      2
    

    因为count 适用于data.frametbl_df,而不是在summarise 内的单个列中


    或使用data.table

    library(data.table)
    setDT(df)[, .(count = .N, count1 = sum(age < 21)), id]
    

    base R

    cbind(count = rowSums(table(df[-2])), count1 = as.vector(rowsum(+(df$age < 21), df$id)))
    #   count count1
    #A1     4      1
    #A2     3      2
    

    或者在sum的基础上使用aggregate

    do.call(data.frame, aggregate(age~id, df, FUN =
                function(x) c(count = length(x), count1 = sum(x<21))))
    

    注意:以上所有方法都为数据集提供了适当的列。这将在aggregate 中特别指出。这就是输出列(即矩阵)使用do.call(data.frame 转换为适当列的原因

    【讨论】:

      【解决方案2】:

      使用基数 R,我们可以使用 aggregate 来查找每个组的行数 (id) 以及值小于 21 的行数

      aggregate(age~id, df, function(x) c(count = length(x), 
                                                         count1 = length(x[x  < 21])))
      
      #  id age.count age.count1
      #1 A1         4          1
      #2 A2         3          2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        • 2020-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多