How to find the mean of corresponding elements of multiple matrices in R?
-
10-09-2020 - |
Pregunta
How to find the mean of corresponding elements of multiple matrices in R?
If the elements of multiple matrices represent the same type of characteristic then we might want to find the mean of those elements. For example, if we have matrices M1, M2, M3, and M4 stored in a list and the first element represent the rate of a particular thing, say Rate of decay of rusty iron during rainy season, then we might want to find the mean of first element of matrix M1, M2, M3, and M4. This mean can be found by using Reduce function.
Example
Consider the below matrices and their list −
> M1<-matrix(1:25,nrow=5) > M1
Output
[,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
> M2<-matrix(1:25,nrow=5) > M3<-matrix(1:25,nrow=5) > M4<-matrix(1:25,nrow=5) > List_M<-list(M1,M2,M3,M4) > List_M
Output
[[1]] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 [[2]] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 [[3]] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 [[4]] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
Finding the mean of corresponding elements in each matrix −
> Reduce("+",List_M)/length(List_M)
Output
[,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
Let’s have a look at another example −
Example
> M1<-matrix(sample(1:10,16,replace=TRUE),ncol=4) > M1
Output
[,1] [,2] [,3] [,4] [1,] 6 7 3 2 [2,] 10 10 3 1 [3,] 7 6 6 5 [4,] 6 7 3 10
Example
> M2<-matrix(sample(1:10,16,replace=TRUE),ncol=4) > M2
Output
[,1] [,2] [,3] [,4] [1,] 9 2 5 7 [2,] 9 4 4 3 [3,] 4 6 8 6 [4,] 3 7 7 5
Example
> M3<-matrix(sample(1:10,16,replace=TRUE),ncol=4) > M3
Output
[,1] [,2] [,3] [,4] [1,] 2 10 3 8 [2,] 8 10 2 8 [3,] 9 6 2 6 [4,] 8 8 6 9
Example
> M4<-matrix(sample(1:10,16,replace=TRUE),ncol=4) > M4
Output
[,1] [,2] [,3] [,4] [1,] 8 3 8 5 [2,] 7 5 5 7 [3,] 1 9 1 4 [4,] 10 1 8 9
Example
> List_new<-list(M1,M2,M3,M4) > List_new
Output
[[1]] [,1] [,2] [,3] [,4] [1,] 6 7 3 2 [2,] 10 10 3 1 [3,] 7 6 6 5 [4,] 6 7 3 10 [[2]] [,1] [,2] [,3] [,4] [1,] 9 2 5 7 [2,] 9 4 4 3 [3,] 4 6 8 6 [4,] 3 7 7 5 [[3]] [,1] [,2] [,3] [,4] [1,] 2 10 3 8 [2,] 8 10 2 8 [3,] 9 6 2 6 [4,] 8 8 6 9 [[4]] [,1] [,2] [,3] [,4] [1,] 8 3 8 5 [2,] 7 5 5 7 [3,] 1 9 1 4 [4,] 10 1 8 9
> Reduce("+",List_new)/length(List_new)
Output
[,1] [,2] [,3] [,4] [1,] 6.25 5.50 4.75 5.50 [2,] 8.50 7.25 3.50 4.75 [3,] 5.25 6.75 4.25 5.25 [4,] 6.75 5.75 6.00 8.25
Advertisements
No afiliado a Tutorialspoint