我有一个包含三列的数据框 (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
逻辑:
当前代码:
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"
最佳答案
我们需要做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.frame
或 tbl_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
或使用
aggregate
基于 sum
do.call(data.frame, aggregate(age~id, df, FUN =
function(x) c(count = length(x), count1 = sum(x<21))))
注意:上述所有方法都为数据集提供了适当的列。这将在
aggregate
中特别注明.这就是输出列(即矩阵)转换为具有 do.call(data.frame
的适当列的原因
关于r - 数据框中的条件计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820559/