如何将矩阵行转换为 R 中的列表?
根据我们的目标,可能需要将矩阵行转换为列表,这意味着每一行都将是列表的一个元素。这可以通过使用该函数来完成,as.list但首先我们需要在转置后将矩阵转换为数据帧。例如,如果我们有一个名为 M 的矩阵,那么它将使用下面的命令将其行转换为列表 -
as.list(data.frame(t(M)))
示例 1
M1<−matrix(1:25,nrow=5)输出结果M1
[,1] [,2] [,3] [,4] [,5][1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
示例
as.list(data.frame(t(M1)))输出结果
$X1[1] 1 6 11 16 21
$X2
[1] 2 7 12 17 22
$X3
[1] 3 8 13 18 23
$X4
[1] 4 9 14 19 24
$X5
[1] 5 10 15 20 25
例2
M2<−matrix(rnorm(36),nrow=6)输出结果M2
[,1] [,2] [,3] [,4] [,5] [,6][1,] 1.320181 0.17152409 −1.76634091 −0.48085533 −1.6186915 −1.4374249
[2,] −0.220481 −0.31776877 −2.16503900 −1.04481201 −1.2440593 −0.5943860
[3,] −0.138843 1.24491033 −0.23453374 0.09363227 0.1624981 −2.2085699
[4,] −0.535679 1.05556228 1.27692225 −1.00761472 −0.6388036 0.2438138
[5,] 1.563999 −0.08637959 −0.10161734 −3.03514376 −0.2729878 −0.4657192
[6,] 1.252191 2.09451091 −0.04484482 −0.96138526 1.2211188 −0.5685082
示例
as.list(data.frame(t(M2)))输出结果
$X1[1] 1.3201811 0.1715241 −1.7663409 −0.4808553 −1.6186915 −1.4374249
$X2
[1] −0.2204810 −0.3177688 −2.1650390 −1.0448120 −1.2440593 −0.5943860
$X3
[1] −0.13884303 1.24491033 −0.23453374 0.09363227 0.16249808 −2.20856995
$X4
[1] −0.5356790 1.0555623 1.2769222 −1.0076147 −0.6388036 0.2438138
$X5
[1] 1.56399912 −0.08637959 −0.10161734 −3.03514376 −0.27298782 −0.46571917
$X6
[1] 1.25219067 2.09451091 −0.04484482 −0.96138526 1.22111884 −0.56850819
例3
M3<−matrix(rpois(16,2),ncol=4)输出结果M3
[,1] [,2] [,3] [,4][1,] 1 2 2 2
[2,] 0 5 1 3
[3,] 1 4 3 1
[4,] 0 1 4 2
示例
as.list(data.frame(t(M3)))输出结果
$X1[1] 1 2 2 2
$X2
[1] 0 5 1 3
$X3
[1] 1 4 3 1
$X4
[1] 0 1 4 2
例4
M4<−matrix(runif(25,2,10),nrow=5)输出结果M4
[,1] [,2] [,3] [,4] [,5][1,] 9.470178 3.844069 3.126983 7.666309 8.801446
[2,] 4.517685 6.602599 6.353498 9.570915 2.854464
[3,] 5.104221 5.793673 4.875067 6.810684 2.926270
[4,] 2.694206 4.677686 8.749031 6.201677 4.149385
[5,] 2.085755 9.849269 9.084727 3.010815 7.153298
示例
as.list(data.frame(t(M4)))输出结果
$X1[1] 9.470178 3.844069 3.126983 7.666309 8.801446
$X2
[1] 4.517685 6.602599 6.353498 9.570915 2.854464
$X3
[1] 5.104221 5.793673 4.875067 6.810684 2.926270
$X4
[1] 2.694206 4.677686 8.749031 6.201677 4.149385
$X5
[1] 2.085755 9.849269 9.084727 3.010815 7.153298
例5
M5<−matrix(rexp(16),nrow=4)输出结果M5
[,1] [,2] [,3] [,4][1,] 1.4500225 1.2780952 3.8074267 0.5150933
[2,] 0.6914497 3.0919047 4.9547217 1.5925355
[3,] 0.6407890 0.1222374 1.3573294 1.1416469
[4,] 1.0918338 1.1835358 0.8053099 0.2225276
示例
as.list(data.frame(t(M5)))输出结果
$X1[1] 1.4500225 1.2780952 3.8074267 0.5150933
$X2
[1] 0.6914497 3.0919047 4.9547217 1.5925355
$X3
[1] 0.6407890 0.1222374 1.3573294 1.1416469
$X4
[1] 1.0918338 1.1835358 0.8053099 0.2225276
以上是 如何将矩阵行转换为 R 中的列表? 的全部内容, 来源链接: utcz.com/z/335647.html