You can use one of the following two methods to quickly create a matrix from vectors in R:
Method 1: Use cbind() to bind vectors into matrix by columns
my_matrix
Method 2: Use rbind() to bind vectors into matrix by rows
my_matrix
The following examples show how to use each method in practice.
Method 1: Use cbind() to Bind Vectors into Matrix by Columns
The following code shows how to use cbind() to bind together three vectors into a matrix by columns:
#define vectors vector1 #column-bind vectors together into matrix my_matrix #view resulting matrix my_matrix vector1 vector2 vector3 [1,] 1 2 3 [2,] 2 4 6 [3,] 3 6 9 [4,] 4 8 12 [5,] 5 10 15 [6,] 6 12 18 [7,] 7 14 21 [8,] 8 16 24 [9,] 9 18 27 [10,] 10 20 30 #view dimensions of matrix dim(my_matrix) [1] 10 3
We can see that the result is a matrix with 10 rows and 3 columns, with each of the three original vectors representing a unique column.
Method 2: Use rbind() to Bind Vectors into Matrix by Rows
The following code shows how to use rbind() to bind together three vectors into a matrix by columns:
#define vectors vector1 #row-bind vectors together into matrix my_matrix #view resulting matrix my_matrix [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] vector1 1 2 3 4 5 6 7 8 9 10 vector2 2 4 6 8 10 12 14 16 18 20 vector3 3 6 9 12 15 18 21 24 27 30 #view dimensions of matrix dim(my_matrix) [1] 3 10
We can see that the result is a matrix with 3 rows and 10 columns, with each of the three original vectors representing a unique row.
Note: In these examples, we chose to bind together three vectors into a matrix, but we can use this exact syntax to bind together any number of vectors we’d like into a matrix.
Additional Resources
The following tutorials explain how to perform other common functions in R:
How to Convert Data Frame Column to Vector in R
How to Convert Matrix to Vector in R
How to Create an Empty Matrix in R
How to Create an Empty Vector in R