[R-lang] apply through a list
Stefan Evert (schtepf.de)
schtepf at schtepf.de
Sat May 19 00:45:04 PDT 2007
On 16 May 2007, at 22:43, Michael Cysouw wrote:
> unfortunatly not: "lapply" applies a function to every element in a
> list - I am trying to do something with a recurrent part of each
> element in the list.
>
lapply() can't do that because the element in a list might be totally
different object, matrices with different dimensions, etc.
In order to sum corresponding entries for a set of matrices (which is
the basic operation needed for you average example), you have to
combine them in a 3-dimensional array, stacking them on top of each
other along the third dimension. The following code should do the
trick, but doesn't check for error conditions etc. (e.g. it assumes
that all elements in the list are indeed matrices with the same
dimensions, and it will fail horribly if this isn't the case).
## input: L is the list of matrices to be averaged
d <- dim(L[[1]]) # get matrix dimensions
A <- array(unlist(L), dim=c(d, length(L))) # convert into array
(first 2 dims = matrix, 3rd dim = stack)
M.avg <- apply(A, 1:2, mean) # apply mean() to 3rd dim for every
entry in dims 1:2
Here's a simple trick to add up the matrices without constructing an
array, though it doesn't generalise as easily to arbitrary functions
and requires a global variable, so it cannot safely be encapsulated
in a general-purpose function:
M.sum <- 0
lapply(L, function (M) { M.sum <<- M.sum + M }) # note the double arrow
M.avg <- M.sum / length(L)
Best wishes,
Stefan
--
"Ecchi nanoha ikenai to omoimasu."
stefan.evert at uos.de
purl.org/stefan.evert
More information about the R-lang
mailing list