聚合 + 均值 returns 错误结果

aggregate + mean returns wrong result

使用 R,我将使用 aggregate(..., mean) 计算分组均值。然而,平均值 return 是错误的。

testdata <-read.table(text="
a  b    c   d   year
2   10  1   NA  1998
1   7   NA  NA  1998
4   6   NA  NA  1998
2   2   NA  NA  1998
4   3   2   1   1998
2   6   NA  NA  1998
3   NA  NA  NA  1998
2   7   NA  3   1998
1   8   NA  4   1998
2   7   2   5   1998
1   NA  NA  4   1998
2   5   NA  6   1998
2   4   NA  NA  1998
3   11  2   7   1998
1   18  4   10  1998
3   12  7   5   1998
2   17  NA  NA  1998
2   11  4   5   1998
1   3   1   1   1998
3   5   1   3   1998
",header=TRUE,sep="")
aggregate(. ~ year, testdata,
          function(x) c(mean = round(mean(x, na.rm=TRUE), 2)))
colMeans(subset(testdata, year=="1998", select=d), na.rm=TRUE)

aggregate 表示组 1998d 的平均值是 4.62,但它是 4.5。

将数据减少到仅一列,aggregate 正确:

aggregate(. ~ year, test[4:5],
          function(x) c(mean = round(mean(x, na.rm=TRUE), 2)))

我的 aggregate() + mean() 函数有什么问题?

aggregate 在将任何列中包含 NA 的行传递给 mean 函数之前将其取出。尝试 运行 没有 na.rm=TRUE 的聚合调用 - 它仍然有效。

要解决此问题,您需要将默认的 na.action 合计更改为 na.pass:

aggregate(. ~ year, testdata,
          function(x) c(mean = round(mean(x, na.rm=TRUE), 2)), na.action = na.pass)


  year    a    b    c   d
1 1998 2.15 7.89 2.67 4.5