Mean of elements in a list of data.frames

自作多情 提交于 2019-11-29 23:32:12

Here is a one liner with plyr. You can replace mean with any other function that you want.

ans1 = aaply(laply(all.dat, as.matrix), c(2, 3), mean)

You would have an easier time changing the data structure, combining the three two dimensional matrices into a single 3 dimensional array (using the abind library). Then the solution is more direct using apply and specifying the dimensions to average over.

EDIT:

When I answered the question, it was tagged homework, so I just gave an approach. The original poster removed that tag, so I will take him/her at his/her word that it isn't.

library("abind")

all.matrix <- abind(all.dat, along=3)
apply(all.matrix, c(1,2), mean)

I gave one answer that uses a completely different data structure to achieve the result. This answer uses the data structure (list of data frames) given directly. I think it is less elegant, but wanted to provide it anyway.

Reduce(`+`, all.dat) / length(all.dat)

The logic is to add the data frames together element by element (which + will do with data frames), then divide by the number of data frames. Using Reduce is necessary since + can only take two arguments at a time (and addition is associative).

Another approach using only base functions to change the structure of the object:

listVec <- lapply(all.dat, c, recursive=TRUE)
m <- do.call(cbind, listVec)

Now you can calculate the mean with rowMeans or the median with apply:

means <- rowMeans(m)
medians <- apply(m, 1, median)

I would take a slightly different approach:

library(plyr)
tmp <- ldply(all.dat) # convert to df
tmp$counter <- 1:5 # 1:12 for your actual situation
ddply(tmp, .(counter), function(x) colMeans(x[2:ncol(x)]))

Couldn't you just use nested lapply() calls?

This appears to give the correct result on my machine

mean.dat <- lapply(all.dat, function (x) lapply(x, mean, na.rm=TRUE))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!