Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Using apply on a multidimensional array in R

I am wondering how to use apply on a multidimensional array. I have something like the following:

A <- array(0, c(2, 2, 5))
for(i in 1:5) {
  A[, , i] <- matrix(rnorm(4), 2, 2)
}

I would like to take the average of those slices to get a single 2 by 2 matrix. Any way I come up with is pretty kludgy.

I was hoping to be able to use apply, like I would if I wanted the average say of the columns of a matrix:

B <- matrix(rnorm(10), 5, 2)
B.mean <- apply(B, 2, mean)

But this doesn't seem to work the way I think it might with 3D arrays:

A.mean <- apply(A, 3, mean)

I appreciate your suggestions.

question from:https://stackoverflow.com/questions/3197330/using-apply-on-a-multidimensional-array-in-r

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

1 Answer

0 votes
by (71.8m points)
A.mean <- apply(A, c(1,2), mean)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...