I have a function that returns a list of vectors and matrices. I then create a variable that is a list of several of the resulting lists from calls to the function. So I have a list of lists. My question is how do I apply a function over the elements of these lists (note this is not the same as applying a function over the lists themselves). Here is a simple example that retains all the essential features of what I am doing
numtrials = 5
x = rep(list(NULL),numtrials)
testfunction = function(){return( list( c(1,2,3,4,5), matrix(runif(10), 2,5),
matrix(0,2,2) ) )}
for(index in 1:numtrials){
x[[index]] = testfunction()
}
I want to now calculate the mean of say the (2,3) element of x[[index]][[2]]
across all "index" lists. Or even better get a matrix of means, xbar
, such that xbar[i,j] = mean(x[[]][[2]][i,j])
. I tried to play around with (and of course read the help file for) lapply
, and apply
, but couldn't get it to work. One of the reasons is that x[[]][[2]][i,j]
appears to be invalid notation
Error in x[[]] : invalid subscript type 'symbol'
I think R doesn't know what to make of the "[[]]
". I know some people are going to suggest vectorizing but note that my function returns matrices and vectors of different, unrelated dimensions (although I am not opposed to vectorizing if you have a clever way of doing this).
Using abind
you can create a list which contains arrays for the relevent components of the internal lists..
eg
library(abind)
xl <- do.call(mapply, c('abind', x, rev.along = 0))
# the second element from each inner list is now within a 3-d array
# which is the 2nd element of xl
# you can now construct your matrix of mean values by using `apply`
means <- apply(xl[[2]], 1:2, mean)
means
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.4576039 0.5185270 0.7099742 0.3812656 0.4529965
## [2,] 0.6528345 0.2304651 0.5534443 0.4404609 0.7361132
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With