简体   繁体   中英

for loop on a list of matrix and the mean of all the matrix in R

I have a list that contain matrix named from 1 to 10 each one represent a year, so i have to generate matrix MG between M1 and M2, also between M2 et M3, M3 et M4....

so for example to calculate matrix betweem M1 and M2 i have to do this following calculation:

L=c(rowSums(Matrix1)) #(sum of each matrix'row)
K=c(rowSums(MatriX2))

G=L+K 

SM=Matrix1+Matrix2  #( sum of the two matrix)

MG=sweep(SM,1,G,FUN = "/") #( div SM by G )

output=list(MG)

and at the end generate a matrix that calculate the mean of all the MG included in the list.

I'm still new in R, any help would be appreciated thanks

It's good that you have your several matrices into a list, we'll use Lapply on those to create a list of i-1 MG matrices, using your code (I didn't check it, just copied it into the function).

your_list <- list(M1 = as.matrix(iris[1:5,1:4]),
                  M2 = as.matrix(iris[6:10,1:4]),
                  M3 = as.matrix(iris[11:15,1:4]))  

your_function <- function(Matrix1,Matrix2){
  L=c(rowSums(Matrix1)) #(sum of each matrix'row)
  K=c(rowSums(Matrix2))
  G=L+K 
  SM=Matrix1+Matrix2  #( sum of the two matrix)
  MG=sweep(SM,1,G,FUN = "/") #( div SM by G )
}

MG_list <- lapply(1:(length(your_list)-1),function(i) your_function(your_list[[i]],your_list[[i+1]]))

Then to do an average of all these matrices we start by summing them, then divide by the number of matrices, see ?Reduce to understand how it works :

avg_MG <- Reduce(`+`,MG_list) / length(MG_list)

An alternative to @Moody_Mudskippers approach would be to use Map .

Example data:

set.seed(1)
matlist <- list(matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
                matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2))
names(matlist) <- paste0("M", 1:10)

Generate output of consecutively swept matrices:

output <- Map(function(x, y){
  sweep(x+y, 1, rowSums(x)+rowSums(y), FUN = "/")
}, matlist[-10], matlist[-1])

Calculate means:

Reduce(`+`, output) / length(output)

          [,1]      [,2]
[1,] 0.4984006 0.5015994
[2,] 0.4730748 0.5269252

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM