How to convert matrix columns to a list of vectors in R?


If we want to use columns of a matrix as a vector then we can convert them in a list of vectors. To convert matrix columns to a list of vectors, we first need to convert the matrix to a data frame then we can read it as list. This can be done as as.list(as.data.frame(matrix_name)).

Example

Consider the below matrix −

> M<-matrix(1:25,nrow=5)
> M
[,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

Converting matrix M columns to vectors −

> V<-as.list(as.data.frame(M))
> V
$V1
[1] 1 2 3 4 5
$V2
[1] 6 7 8 9 10
$V3
[1] 11 12 13 14 15
$V4
[1] 16 17 18 19 20
$V5
[1] 21 22 23 24 25
> str(V)
List of 5
$ V1: int [1:5] 1 2 3 4 5
$ V2: int [1:5] 6 7 8 9 10
$ V3: int [1:5] 11 12 13 14 15
$ V4: int [1:5] 16 17 18 19 20
$ V5: int [1:5] 21 22 23 24 25

Checking whether V1, V2, V3, V4, and V5 are vectors or not −

> is.vector(V$V1)
[1] TRUE
> is.vector(V$V2)
[1] TRUE
> is.vector(V$V3)
[1] TRUE
> is.vector(V$V4)
[1] TRUE
> is.vector(V$V5)
[1] TRUE

Converting non-square matrix columns to vector list −

> M_new<-matrix(1:50,nrow=5)
> M_new
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1    6   11   16   21   26   31   36   41    46
[2,] 2    7   12   17   22   27   32   37   42    47
[3,] 3    8   13   18   23   28   33   38   43    48
[4,] 4    9   14   19   24   29   34   39   44    49
[5,] 5   10   15   20   25   30   35   40   45    50
> V_new<-as.list(as.data.frame(M_new))
> V_new
$V1
[1]  1  2  3  4  5
$V2
[1]  6  7  8  9 10
$V3
[1] 11 12 13 14 15
$V4
[1] 16 17 18 19 20
$V5
[1] 21 22 23 24 25
$V6
[1] 26 27 28 29 30
$V7
[1] 31 32 33 34 35
$V8
[1] 36 37 38 39 40
$V9
[1] 41 42 43 44 45
$V10
[1] 46 47 48 49 50

Updated on: 11-Aug-2020

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements