如何在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"