r - 按两个或多个因子变量进行汇总统计?

标签 r summary

这最好用一个例子来说明

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/

相关文章:

r - 如何通过 R 中数据帧的字符串向量运行 for 循环?

r - 如何取消 data.table 中的列表列分组?

mysql - SQL向MySQL结果集添加汇总行

Android首选项摘要默认颜色?

r - 分面时使用 stat_summary 为折线图生成误差线的问题

mysql - MYSQL中,如何根据查询中未指定的参数汇总查询结果?

r - 如何从 R 中的随机森林中获取单个树的概率?

r - 行尾的额外逗号导致 read.csv 和 read.table 出错

R 不区分大小写的捕获组

java - 如何修复 Javadoc 注释有解析错误,详细信息 : no viable alternative at input ' *' while parsing JAVADOC_TAG [NonEmptyAtClauseDescription]