6.2 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Convert List to Matrix in R (With Examples)

How to Convert List to Matrix in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to convert a list to a matrix in R:

#convert list to matrix (by row)
matrix(unlist(my_list), ncol=3, byrow=TRUE)

#convert list to matrix (by column)
matrix(unlist(my_list), ncol=3)

The following examples show how to use this syntax in practice.

Example 1: Convert List to Matrix (By Rows)

The following code shows how convert a list to a matrix (by rows) in R:

#create list
my_list #view list
my_list

[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] 7 8 9

[[4]]
[1] 10 11 12

[[5]]
[1] 13 14 15

#convert list to matrix
matrix(unlist(my_list), ncol=3, byrow=TRUE)

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12
[5,]   13   14   15

The result is a matrix with 5 rows and 3 columns.

Example 2: Convert List to Matrix (By Columns)

The following code shows how to convert a list to a matrix (by columns) in R:

#create list
my_list #view list
my_list

[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

[[3]]
[1] 11 12 13 14 15

#convert list to matrix
matrix(unlist(my_list), ncol=3)

     [,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15

The result is a matrix with 5 rows and 3 columns.

Cautions on Converting a List to Matrix

Note that R will throw an error if you attempt to convert a list to a matrix in which each position of the list doesn’t have the same number of elements.

The following example illustrates this point:

#create list
my_list #view list
my_list

[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

[[3]]
[1] 11 12 13

#attempt to convert list to matrix
matrix(unlist(my_list), ncol=3)

Warning message:
In matrix(unlist(my_list), ncol = 3) :
  data length [13] is not a sub-multiple or multiple of the number of rows [5]

Additional Resources

The following tutorials explain how to perform other common conversions in R:

How to Convert List to Vector in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories