如果我们有一个矩阵,则出于某些分析目的,可能希望将其转换为单列矩阵,例如与矩阵中长度等于元素总数的向量相乘。因此,可以通过使用矩阵函数本身将矩阵转换为单列矩阵,但是为此,我们需要使列名和行名无效。
> M1<-matrix(rnorm(20),nrow=5) > M1
输出结果
[,1] [,2] [,3] [,4] [1,] -0.8067677 1.9855697 -2.5012312 1.01283626 [2,] -0.5107091 0.4632027 -1.3966282 0.02534344 [3,] -0.5564871 0.2924344 -0.8991352 -0.50715002 [4,] 0.2411252 -0.5139827 -1.3272964 -0.50694324 [5,] -0.5753370 -1.2357388 0.2028664 0.26498877
> matrix(M1,dimnames=list(t(outer(colnames(M1),rownames(M1),FUN=paste)),NULL))
输出结果
[,1] [1,] -0.80676768 [2,] -0.51070906 [3,] -0.55648712 [4,] 0.24112516 [5,] -0.57533702 [6,] 1.98556973 [7,] 0.46320275 [8,] 0.29243441 [9,] -0.51398265 [10,] -1.23573882 [11,] -2.50123125 [12,] -1.39662824 [13,] -0.89913524 [14,] -1.32729635 [15,] 0.20286643 [16,] 1.01283626 [17,] 0.02534344 [18,] -0.50715002 [19,] -0.50694324 [20,] 0.26498877
> M2<-matrix(rpois(20,5),ncol=2) > M2
输出结果
[,1] [,2] [1,] 6 1 [2,] 6 7 [3,] 4 5 [4,] 6 5 [5,] 4 5 [6,] 5 4 [7,] 4 9 [8,] 4 6 [9,] 3 6 [10,] 8 10
> matrix(M2,dimnames=list(t(outer(colnames(M2),rownames(M2),FUN=paste)),NULL))
输出结果
[,1] [1,] 6 [2,] 6 [3,] 4 [4,] 6 [5,] 4 [6,] 5 [7,] 4 [8,] 4 [9,] 3 [10,] 8 [11,] 1 [12,] 7 [13,] 5 [14,] 5 [15,] 5 [16,] 4 [17,] 9 [18,] 6 [19,] 6 [20,] 10
> M3<-matrix(sample(0:9,20,replace=TRUE),ncol=10) > M3
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 2 2 6 1 7 3 8 6 1 2 [2,] 8 0 4 7 8 8 8 2 1 3
> matrix(M3,dimnames=list(t(outer(colnames(M3),rownames(M3),FUN=paste)),NULL))
输出结果
[,1] [1,] 2 [2,] 8 [3,] 2 [4,] 0 [5,] 6 [6,] 4 [7,] 1 [8,] 7 [9,] 7 [10,] 8 [11,] 3 [12,] 8 [13,] 8 [14,] 8 [15,] 6 [16,] 2 [17,] 1 [18,] 1 [19,] 2 [20,] 3