如何查找 R 列表中存储的每个矩阵的列均值?
要查找 R 列表中存储的所有矩阵的列均值,我们可以结合使用 `sapply` 函数和 `colMeans` 函数。
例如,如果我们有一个名为 LIST 的列表包含一些矩阵,则可以使用以下命令查找每个矩阵的列均值:
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
要在列表中查找每个矩阵的列均值,请将以下代码添加到上面的代码片段中:
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
广告