Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply function to elements over a list

Tags:

r

Sorry for the simple question but I can't think of a good way to take functions elements of a list of data frames. I am sure there is something within the plyr/reshape2 packages but I just can't think of it.

For example I have a list A as follows:

>A
[[1]]
        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]    1    1    1    1    1    1    1    1    1     1
   [2,]    1    1    1    1    1    1    1    1    1     1
   [3,]    1    1    1    1    1    1    1    1    1     1
   [4,]    1    1    1    1    1    1    1    1    1     1
   [5,]    1    1    1    1    1    1    1    1    1     1

[[2]]
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    2    2    2    2    2    2    2    2    2     2
 [2,]    2    2    2    2    2    2    2    2    2     2
 [3,]    2    2    2    2    2    2    2    2    2     2
 [4,]    2    2    2    2    2    2    2    2    2     2
 [5,]    2    2    2    2    2    2    2    2    2     2

Say I want to take the mean across the corresponding elements of the matrices in the list. One way to do this would be

Reduce("+",A)/length(A)

I can't seem to feed Reduce() more complex functions and assume there is a better way in general.

like image 507
scottyaz Avatar asked Aug 16 '11 21:08

scottyaz


People also ask

How do you apply a function to each element of a list?

The best way to apply a function to each element of a list is to use the Python built-in map() function that takes a function and one or more iterables as arguments. It then applies the function to each element of the iterables. An alternate way is to use list comprehension.

How do you apply a function to all elements of a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.


2 Answers

In this case, maybe you're better off with your data in an array rather than a list?

#Recreate data
A <- list(a=matrix(1,5,10),b=matrix(2,5,10))

#Convert to array
A1 <- array(do.call(cbind,A),dim = c(5,10,2))

#Better way to convert to array
require(abind)
A1 <- abind(A,along = 3)

#Now we can simply use apply
apply(A1,c(1,2),mean)
like image 197
joran Avatar answered Oct 04 '22 20:10

joran


Maybe do.call?

do.call(`+`, A)/length(A)

Or if you really don't want to abind it into a larger matrix,

array(sapply(seq_along(A[[1]]), function(i) mean(sapply(A,`[`,i))), 
      dim=dim(A[[1]]))
like image 34
Aaron left Stack Overflow Avatar answered Oct 04 '22 19:10

Aaron left Stack Overflow