5

I have to calculate mean of each matrix of an n dimension of array. As I am new in R can anyone help me. For example

M = 4
m = array(1:10, dim= c(10, 1, M))
m
z = matrix(NA, M,1)
for (i in 1:z){
for (j in 1:z){
z[i, j] = mean(m[ , , i])
}
}
z

I tried above way but its incorrect

  • Possible duplicate of [How to get mean, median, and other statistics over entire matrix, array or dataframe?](https://stackoverflow.com/questions/9424311/how-to-get-mean-median-and-other-statistics-over-entire-matrix-array-or-dataf) – h3rm4n Feb 25 '18 at 18:29

2 Answers2

4

1) apply Try apply

apply(m, 3, mean)
## [1] 5.5 5.5 5.5 5.5

2) loop or to do it in a loop:

n <- dim(m)[3]
result <- numeric(n)
for(i in 1:n) result[i] <- mean(m[,,i])
result
## [1] 5.5 5.5 5.5 5.5

3) reshape or reshape it into a matrix and take the column means. n is from above.

colMeans(matrix(m,, n))
## [1] 5.5 5.5 5.5 5.5
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

My understanding is that the mean function provides its answer in the form of a 1 x 1 matrix, which I assume is what you're looking for since you didn't refer to a row-wise or column-wise mean.

Here is some detail on the topic from a previous post: How to get mean, median, and other statistics over entire matrix, array or dataframe?

  • thanks but I am looking mean for per matrix wise in array as I have 4 matrix in above array so my output will be like mean of m[,,1], m[,,2], m[,,3], m[,,4] – Kritika Rajain Feb 25 '18 at 18:25
  • I see, I modified a snippet your existing code to give you an element-wise mean for the array: `z = matrix(NA, M,1) for (i in 1:length(z)){ z[i] = mean(m[, , i]) } z` – Karan RK Raj Feb 25 '18 at 18:41