这最好用一个例子来说明
str(mtcars)
mtcars$gear <- factor(mtcars$gear, labels=c("three","four","five"))
mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
mtcars$am <- factor(mtcars$am, labels=c("manual","auto")
str(mtcars)
tapply(mtcars$mpg, mtcars$gear, sum)
这给了我每个齿轮的总英里数。但是如果我想要一个 3x3 的 table ,上面有齿轮,侧面有圆柱体,还有 9 个带有二元总和的单元格,我将如何“聪明地”得到它。
我可以去。
tapply(mtcars$mpg[mtcars$cyl=="four"], mtcars$gear[mtcars$cyl=="four"], sum)
tapply(mtcars$mpg[mtcars$cyl=="six"], mtcars$gear[mtcars$cyl=="six"], sum)
tapply(mtcars$mpg[mtcars$cyl=="eight"], mtcars$gear[mtcars$cyl=="eight"], sum)
这看起来很麻烦。
那么我将如何在混合中引入第三个变量?
这有点在我正在考虑的空间中。
Summary statistics using ddply
更新 这让我在那里,但它并不漂亮。
aggregate(mpg ~ am+cyl+gear, mtcars,sum)
干杯
最佳答案
这个怎么样,还在用tapply()
?它比你知道的更通用!
with(mtcars, tapply(mpg, list(cyl, gear), sum))
# three four five
# four 21.5 215.4 56.4
# six 39.5 79.0 19.7
# eight 180.6 NA 30.8
或者,如果您希望打印输出更具可解释性:
with(mtcars, tapply(mpg, list("Cylinder#"=cyl, "Gear#"=gear), sum))
如果你想使用两个以上的交叉分类变量,这个想法是完全一样的。结果将在一个 3 维或更多维数组中返回:
A <- with(mtcars, tapply(mpg, list(cyl, gear, carb), sum))
dim(A)
# [1] 3 3 6
lapply(1:6, function(i) A[,,i]) # To convert results to a list of matrices
# But eventually, the curse of dimensionality will begin to kick in...
table(is.na(A))
# FALSE TRUE
# 12 42
关于r - 按两个或多个因子变量进行汇总统计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10220510/