在一次调用中按组对多个变量应用多个汇总函数
x <- read.table(text = " id1 id2 val1 val2 1 a x 1 9 2 a x 2 4 3 a y 3 5 4 a y 4 9 5 b x 1 7 6 b y 4 4 7 b x 3 9 8 b y 2 8", header = TRUE)
# calculate meanaggregate(. ~ id1 + id2, data = x, FUN = mean)# count rowsaggregate(. ~ id1 + id2, data = x, FUN = length)
do.call("rbind", aggregate(. ~ id1 + id2, data = x, FUN = function(x) data.frame(m = mean(x), n = length(x))))
# m n# id1 1 2# id2 1 1# 1.5 2# 2 2# 3.5 2# 3 2# 6.5 2# 8 2# 7 2# 6 2# Warning message:# In rbind(id1 = c(1L, 2L, 1L, 2L), id2 = c(1L, 1L, 2L, 2L), val1 = list( :# number of columns of result is not a multiple of vector length (arg 1)
aggregate
波斯汪
回首忆惘然