如何在 R 中将矩阵列转换为列表?
可以使用 apply 函数将矩阵列转换为列表。使用 as.list 函数将矩阵读作列表。例如,如果我们有一个矩阵称为 M,则使用命令 apply(M,2,as.list) 即可将 M 中的列转换为列表。
示例 1
> M1<-matrix(rnorm(10),ncol=2) > M1
输出
[,1] [,2] [1,] -1.3256074 -0.07328026 [2,] 1.1997584 -1.06542989 [3,] -0.2214659 -1.75903298 [4,] 1.4446361 -0.12859397 [5,] -0.1504967 0.97264445
将 M1 列转换为列表:
> apply(M1,2,as.list)
输出
[[1]] [[1]][[1]] [1] -1.325607 [[1]][[2]] [1] 1.199758 [[1]][[3]] [1] -0.2214659 [[1]][[4]] [1] 1.444636 [[1]][[5]] [1] -0.1504967 [[2]] [[2]][[1]] [1] -0.07328026 [[2]][[2]] [1] -1.06543 [[2]][[3]] [1] -1.759033 [[2]][[4]] [1] -0.128594 [[2]][[5]] [1] 0.9726444
示例 2
> M2<-matrix(rpois(10,5),ncol=2) > M2
输出
[,1] [,2] [1,] 4 7 [2,] 6 7 [3,] 2 4 [4,] 7 2 [5,] 8 1
将 M2 列转换为列表:
> apply(M2,2,as.list)
输出
[[1]] [[1]][[1]] [1] 4 [[1]][[2]] [1] 6 [[1]][[3]] [1] 2 [[1]][[4]] [1] 7 [[1]][[5]] [1] 8 [[2]] [[2]][[1]] [1] 7 [[2]][[2]] [1] 7 [[2]][[3]] [1] 4 [[2]][[4]] [1] 2 [[2]][[5]] [1] 1
示例 3
> M3<-matrix(sample(c("true","false"),10,replace=TRUE),ncol=2) > M3
输出
[,1] [,2] [1,] "true" "false" [2,] "false" "true" [3,] "true" "false" [4,] "false" "true" [5,] "false" "false"
将 M3 列转换为列表:
> apply(M3,2,as.list)
输出
[[1]] [[1]][[1]] [1] "true" [[1]][[2]] [1] "false" [[1]][[3]] [1] "true" [[1]][[4]] [1] "false" [[1]][[5]] [1] "false" [[2]] [[2]][[1]] [1] "false" [[2]][[2]] [1] "true" [[2]][[3]] [1] "false" [[2]][[4]] [1] "true" [[2]][[5]] [1] "false"
广告