You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用aggregate()函数按年龄计算身高体重均值时遇问题求助

解决aggregate()分组计算均值的问题

为什么用mean()会得到全NA?

你的数据里存在缺失值(NA),mean()函数默认遇到NA就直接返回NA——只要分组内有一个缺失值,整组的均值结果就会变成NA。

正确的代码写法

给mean加上na.rm=TRUE参数,让函数忽略缺失值即可:

table1 <- aggregate(data[,c("height", "weight")], by=list(age=data$age), function(x) mean(x, na.rm=TRUE))
View(table1)

也可以用更简洁的公式格式,可读性更强:

table1 <- aggregate(cbind(height, weight) ~ age, data = data, FUN = function(x) mean(x, na.rm=TRUE))
View(table1)

补充:从summary结果中提取均值

如果一定要用summary函数,可通过提取结果里的"Mean"部分来仅获取均值(但这种方法不如直接用mean高效):

table1 <- aggregate(data[,c("height", "weight")], by=list(age=data$age), function(x) summary(x)["Mean"])
View(table1)

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:45:19