How to Convert R Matrix to List

R Matrix is a Vector with attributes of a dimension and optionally, dimension names attached to the Vector. The list is a data structure having elements of different data types. 

Convert R Matrix to List

To convert Matrix to List in R, use the split() function. The split() is an inbuilt R function that divides the data in the vector into the groups defined by f. The replacement forms replace values corresponding to such a division. The unsplit() function reverses the effect of the split.

Syntax

split(x, f, drop = FALSE, …)

Parameters

x: It is a Vector or data frame containing values to be divided into groups.

f: A ‘factor’ in the sense that as.factor(f) defines the grouping or a list of such factors, their interaction is used for the grouping.

drop: logical indicating if levels that do not occur should be dropped (if f is a factor or a list).

Example

mat <- matrix(1:12, nrow = 4)
mat
cat("After converting from matrix to list", "\n")
list <- split(mat, rep(1:ncol(mat), each = nrow(mat)))
list

Output

     [,1] [,2] [,3]
[1,]   1   5    9
[2,]   2   6   10
[3,]   3   7   11
[4,]   4   8   12
After converting from matrix to list
$`1`
[1] 1 2 3 4

$`2`
[1] 5 6 7 8

$`3`
[1] 9 10 11 12

In this example, we have converted 4 X 3 matrix into the list. We have converted a matrix into a list using the split() function. The split() function takes a matrix, rep() function, and each arguments. The rep() is an iteration function in R. The term iteration means repetition.

You can also use the following approach to convert the matrix to a list.

mat <- matrix(1:5)
mat
typeof(mat)
list <- list(x = mat)
list
typeof(list)

Output

     [,1]
[1,]   1
[2,]   2
[3,]   3
[4,]   4
[5,]   5
[1] "integer"
$x
     [,1]
[1,]   1
[2,]   2
[3,]   3
[4,]   4
[5,]   5

[1] "list"

You can also check the class of the matrix and list using the class() function.

mat <- matrix(1:5)
class(mat)
list <- list(x = mat)
class(list)

Output

[1] "matrix" "array"
[1] "list"

Converting matrix columns to a list of vectors

If we need to use columns of a matrix as a vector, then we can convert them into the list of vectors.

To convert matrix columns to a list of vectors, we first need to convert a matrix to a data frame, then we can read it as the list.

Code snippet

as.list(as.data.frame(matrix_name))

See the following code.

mat <- matrix(1:9, nrow = 3)
mat
class(mat)
lst <- as.list(as.data.frame(mat))
lst
class(lst)

Output

     [,1] [,2] [,3]
[1,]   1   4    7
[2,]   2   5    8
[3,]   3   6    9
[1] "matrix" "array"
$V1
[1] 1 2 3

$V2
[1] 4 5 6

$V3
[1] 7 8 9

[1] "list"

That is it for converting a matrix to list in R programming.

See also

R Matrix to Vector

R Vector to Matrix

R List to Matrix

Leave a Comment