如何找到存储在 R 列表中的每个矩阵的列均值?
要查找存储在 R 列表中的所有矩阵的列均值,我们可以使用 sapply 函数和 colMeans 函数。
例如,如果我们有一个名为 LIST 的列表,其中包含一些矩阵,那么可以使用以下命令找到每个矩阵的 col 均值
sapply(LIST,colMeans)
查看以下示例以了解其工作原理。
示例
以下代码段创建矩阵列表 -
M1<-matrix(round(rnorm(45),1),ncol=3)输出结果M2<-matrix(round(rnorm(45),1),ncol=3)
M3<-matrix(round(rnorm(45),1),ncol=3)
M4<-matrix(round(rnorm(45),1),ncol=3)
List<-list(M1,M2,M3,M4)
List
创建以下矩阵 -
[[1]][,1] [,2] [,3]
[1,] -1.6 0.4 -1.5
[2,] 0.1 -0.2 -0.3
[3,] 0.4 0.1 0.4
[4,] 1.2 0.8 -0.1
[5,] -2.0 -1.0 -0.4
[6,] -0.5 0.8 -1.2
[7,] 0.2 -1.0 -3.0
[8,] -0.8 0.1 1.1
[9,] -2.7 -0.4 1.9
[10,] 0.7 -0.9 0.9
[11,] -0.8 -0.1 0.2
[12,] 0.2 -0.4 0.2
[13,] 0.3 -0.8 0.3
[14,] 0.3 -0.8 -0.2
[15,] 1.1 0.4 -0.2
[[2]]
[,1] [,2] [,3]
[1,] -0.4 1.2 -1.6
[2,] 0.4 -0.5 -0.2
[3,] -1.8 -1.2 -0.7
[4,] -1.3 -1.7 1.4
[5,] 0.9 0.2 -0.3
[6,] 0.2 0.7 1.1
[7,] 0.6 0.6 0.4
[8,] 0.2 0.2 -0.2
[9,] -1.0 0.8 -0.7
[10,] -1.0 0.1 -0.1
[11,] -0.7 1.5 -0.2
[12,] -1.3 -0.3 2.2
[13,] 0.9 0.3 0.7
[14,] -0.4 0.7 0.0
[15,] -1.0 1.2 0.6
[[3]]
[,1] [,2] [,3]
[1,] 2.2 -0.1 0.0
[2,] -1.6 0.4 -0.9
[3,] -1.5 -1.0 1.3
[4,] -0.4 -0.2 1.6
[5,] -0.8 -0.7 0.3
[6,] -1.2 -0.1 -0.9
[7,] 0.9 0.9 -1.3
[8,] 1.1 0.9 -0.4
[9,] -0.4 -0.4 0.4
[10,] 1.1 -0.6 0.5
[11,] 0.4 0.8 -0.9
[12,] -0.8 -1.7 0.8
[13,] -1.5 -0.2 0.1
[14,] 0.5 -0.7 -0.7
[15,] -0.7 -0.7 0.6
[[4]]
[,1] [,2] [,3]
[1,] 0.5 -0.8 -1.5
[2,] 0.1 0.3 0.0
[3,] -1.5 0.2 0.5
[4,] 0.8 -1.5 0.2
[5,] 1.0 -1.3 0.5
[6,] 0.0 -1.4 1.2
[7,] 0.0 -1.9 -0.7
[8,] 0.7 -0.5 0.1
[9,] -0.4 -0.1 0.5
[10,] -0.3 -0.6 0.6
[11,] 3.1 0.2 0.3
[12,] 0.9 0.4 -0.4
[13,] -0.1 -1.2 -0.6
[14,] 1.5 -1.1 0.8
[15,] -1.5 -0.2 -1.2
要查找 List 中每个矩阵的列均值,请将以下代码添加到上述代码段中 -
M1<-matrix(round(rnorm(45),1),ncol=3)输出结果M2<-matrix(round(rnorm(45),1),ncol=3)
M3<-matrix(round(rnorm(45),1),ncol=3)
M4<-matrix(round(rnorm(45),1),ncol=3)
List<-list(M1,M2,M3,M4)
sapply(List,colMeans)
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
[,1] [,2] [,3] [,4][1,] -0.2600000 -0.3800000 -0.18000000 0.3200000
[2,] -0.2000000 0.2533333 -0.22666667 -0.6333333
[3,] -0.1266667 0.1600000 0.03333333 0.0200000
以上是 如何找到存储在 R 列表中的每个矩阵的列均值? 的全部内容, 来源链接: utcz.com/z/341286.html