Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

r - apply function to elements over a list

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...