# How to convert a matrix column into list in R?

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

To convert a matrix column into list can be done by using the apply function. We will have to read the columns of the matrix as list by using as.list function. For example, if we have a matrix called M then the columns in M can be converted into list by using the command apply(M,2,as.list).

## Example1

Live Demo

> M1<-matrix(rnorm(10),ncol=2)
> M1

## Output

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

Converting M1 columns to a list −

> apply(M1,2,as.list)

## Output

[]
[][]
 -1.325607

[][]
 1.199758

[][]
 -0.2214659

[][]
 1.444636

[][]
 -0.1504967

[]
[][]
 -0.07328026

[][]
 -1.06543

[][]
 -1.759033

[][]
 -0.128594

[][]
 0.9726444

## Example2

Live Demo

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

## Output

     [,1] [,2]
[1,]    4    7
[2,]    6    7
[3,]    2    4
[4,]    7    2
[5,]    8    1

Converting M2 columns to a list −

> apply(M2,2,as.list)

## Output

[]
[][]
 4

[][]
 6

[][]
 2

[][]
 7

[][]
 8

[]
[][]
 7

[][]
 7

[][]
 4

[][]
 2

[][]
 1

## Example3

Live Demo

> M3<-matrix(sample(c("true","false"),10,replace=TRUE),ncol=2)
> M3

## Output

     [,1]    [,2]
[1,] "true"  "false"
[2,] "false" "true"
[3,] "true"  "false"
[4,] "false" "true"
[5,] "false" "false"


Converting M3 columns to a list −

> apply(M3,2,as.list)

## Output

[]
[][]
 "true"

[][]
 "false"

[][]
 "true"

[][]
 "false"

[][]
 "false"

[]
[][]
 "false"

[][]
 "true"

[][]
 "false"

[][]
 "true"

[][]
 "false"