r/rstats•
erlo

Nesting "apply" within "lapply" to aggregate matrices within a list

Hello,

I've searched online and I can't figure this one out. I'm new to R, and so I was hoping that I can do this without having to use a for loop.

Let's say I have a list(), in which each element of the list is an NxM matrix.

If I want to get the sum() of the columns in one of the matrices, I would use apply(Matrix1, MARGIN=2,FUN=sum). But I want to use apply() across all elements of the list.

Thus I tried to use lapply(), and pass apply() within it.

Here's the sample code:

A1<-matrix(1:30,10,3)

A2<-matrix(31:60,10,3)

A3<-matrix(61:90,10,3)

A<-list(A1=A1,A2=A2,A3=A3)

lapply(A,apply,MARGIN=2,FUN=sum)

However, I get the following error:

"Error in FUN(X[[1L]], ...) : invalid 'type' (closure) of argument"

If I were to run this line, however, I get results:

apply(A[[1]],MARGIN=2,FUN=sum)

What I'm doing instead is running the apply() in a for-loop, but something tells me that's not optimal. Any feedback would be helpful.

Thank you

Posted Jun 27, 2014, 1:12 AM UTC

10

No comments yet

Nobody commented on this post, or the comments weren't captured.