我有一个类似下面的列表,其中包含我想要对其进行单独操作的矩阵。
data <- data.frame(matrix(data = c(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2), nrow = 8, ncol = 4, byrow = TRUE) )
matrix_list <- list(data[1:4, ], data[5:8, ])
我知道我可以分别对每个对象进行矩阵运算,比如
eigen(matrix_list[[1]])
我可以使用for
循环
for (i in 1:2){print(eigen((data_list[[i]])))}
如何跳过for
循环并直接在列表中操作?如果我能做一些像“eigen(matrix_list)”
答案 0 :(得分:3)
使用lapply
操作列表
lapply(matrix_list, eigen)
[[1]]
[[1]]$values
[1] 1 1 1 1
[[1]]$vectors
[,1] [,2] [,3] [,4]
[1,] 0 0 0 1
[2,] 0 0 1 0
[3,] 0 1 0 0
[4,] 1 0 0 0
[[2]]
[[2]]$values
[1] 2 2 2 2
[[2]]$vectors
[,1] [,2] [,3] [,4]
[1,] 0 0 0 1
[2,] 0 0 1 0
[3,] 0 1 0 0
[4,] 1 0 0 0
如果您只对值或向量感兴趣,可以使用以下方法选择它们:
Eigen <- lapply(matrix_list, eigen)
> sapply(Eigen, '[', 'values') # Extrating eigen values
$values
[1] 1 1 1 1
$values
[1] 2 2 2 2
> sapply(Eigen, '[', 'vectors') # Extrating eigen vectors
$vectors
[,1] [,2] [,3] [,4]
[1,] 0 0 0 1
[2,] 0 0 1 0
[3,] 0 1 0 0
[4,] 1 0 0 0
$vectors
[,1] [,2] [,3] [,4]
[1,] 0 0 0 1
[2,] 0 0 1 0
[3,] 0 1 0 0
[4,] 1 0 0 0
>