1

我有一个数据帧 x 的列表,我想找到数据帧中每个元素的平均值。我在网上找到了一个由 Dimitris Rizopoulos 提供的优雅解决方案。

x.mean = Reduce("+", x) / length(x) 

但是,当数据帧包含 NA 时,这实际上不起作用。有没有什么好方法可以做到这一点?

4

2 回答 2

7

Here is an approach that uses data.table

The steps are (1) coerce each data.frame [element] in x to data.table, with a column (called rn) identifying the rownames. (2) on the large data.table, by rowname calculate the mean of each column (with na.rm = TRUE dealing with NA values). (3) remove the rn column

library(data.table)


results <- rbindlist(lapply(x,data.table, keep.rownames = TRUE))[,
                     lapply(.SD, mean,na.rm = TRUE),by=rn][,rn := NULL]

an alternative would be to coerce to matrix, "simplify" to a 3-dimensional array then apply a mean over the appropriate margins

    # for example

    results <- as.data.frame(apply(simplify2array(lapply(x, as.matrix)),1:2,mean, na.rm = TRUE))
于 2013-08-22T03:40:04.737 回答
5

我更喜欢@mnel 的解决方案,但作为一个教育练习,您可以修改表达式以使用NA值,同时保持相同类型的逻辑:

Reduce(function(y,z) {y[is.na(y)] <- 0; z[is.na(z)] <- 0; y + z}, x) /
  Reduce('+', lapply(x, function(y) !is.na(y)))
于 2013-08-22T04:26:05.013 回答