Table of Contents
In R, you can combine a list of matrices into a single matrix using the do.call() function. This function takes in the list of matrices as the first argument and c, or the concatenation function, as the second argument. The c function combines the matrices in the list and returns a single matrix as the output. This is the simplest way to combine a list of matrices in R.
You can use the following methods to combine a list of matrices in R:
Method 1: Combine List of Matrices by Rows
do.call(rbind, list_of_matrices)
Method 2: Combine List of Matrices by Columns
do.call(cbind, list_of_matrices)
The following examples show how to use each method in practice with the following two matrices in R:
#define matrices matrix1 <- matrix(1:6, nrow=3) matrix2 <- matrix(7:12, nrow=3) #view first matrix matrix1 [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 #view second matrix matrix2 [,1] [,2] [1,] 7 10 [2,] 8 11 [3,] 9 12
Example 1: Combine List of Matrices by Rows
The following code shows how to use the function to combine a list of matrices by rows:
#create list of matrices
matrix_list <- list(matrix1, matrix2)
#combine into one matrix by rows
do.call(rbind, matrix_list)
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[4,] 7 10
[5,] 8 11
[6,] 9 12
The two matrices have been combined into a single matrix by rows.
Example 2: Combine List of Matrices by Columns
The following code shows how to use the function to combine a list of matrices by columns:
#create list of matrices
matrix_list <- list(matrix1, matrix2)
#combine into one matrix by columns
do.call(cbind, matrix_list)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
The two matrices have been combined into a single matrix by columns.
Related: