How to convert a matrix into a matrix with single column in R?


If we have a matrix then we might want to convert it to matrix with single column for some analytical purpose such as multiplying with a vector that has the length equal to the total number of elements as in the matrix. Thus, the matrix can be converted to a single column matrix by using matrix function itself but for this we would need to nullify the column names and row names.

Example1

Live Demo

> M1<-matrix(rnorm(20),nrow=5)
> M1

Output

        [,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

Example

> matrix(M1,dimnames=list(t(outer(colnames(M1),rownames(M1),FUN=paste)),NULL))

Output

         [,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

Example2

Live Demo

> M2<-matrix(rpois(20,5),ncol=2)
> M2

Output

[,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

Example

> matrix(M2,dimnames=list(t(outer(colnames(M2),rownames(M2),FUN=paste)),NULL))

Output

[,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

Example3

Live Demo

> M3<-matrix(sample(0:9,20,replace=TRUE),ncol=10)
> M3

Output

[,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

Example

> matrix(M3,dimnames=list(t(outer(colnames(M3),rownames(M3),FUN=paste)),NULL))

Output

[,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

Updated on: 21-Nov-2020

834 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements