使用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
相关产品推荐
相关产品推荐

