繁体   English   中英

矩阵列表上的for循环以及R中所有矩阵的均值

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

我有一个列表,其中包含从1到10命名的矩阵,每个矩阵代表一年,因此我必须在M1和M2之间,也在M2 et M3,M3 et M4之间生成矩阵MG。

因此,例如要计算M1和M2之间的矩阵,我必须执行以下计算:

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)

最后生成一个矩阵,该矩阵计算列表中所有MG的平均值。

我还是R语言的新手,不胜感激,谢谢

最好将几个矩阵放入列表中,我们将使用您的代码对它们使用Lapply来创建i-1 MG矩阵列表(我没有检查,只是将其复制到了函数中)。

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]]))

然后,要对所有这些矩阵求平均值,我们首先将它们求和,然后除以矩阵数,请参见?Reduce以了解其工作原理:

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

@Moody_Mudskippers方法的替代方法是使用Map

示例数据:

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)

生成连续扫描矩阵的输出:

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

计算均值:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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