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

#convert matrix to vector (sorted by columns) using c() new_vector <- c(my_matrix) #convert matrix to vector (sorted by rows) using c() new_vector <- c(t(my_matrix)) #convert matrix to vector (sorted by columns) using as.vector() new_vector <- as.vector(my_matrix) #convert matrix to vector (sorted by rows) using as.vector() new_vector <- as.vector(t(my_matrix))

Note that the **c()** and **as.vector()** functions will return identical results.

The following examples show how to use each of these functions in practice with the following matrix:

#create matrix my_matrix <- matrix(1:20, nrow = 5) #display matrix my_matrix [,1] [,2] [,3] [,4] [1,] 1 6 11 16 [2,] 2 7 12 17 [3,] 3 8 13 18 [4,] 4 9 14 19 [5,] 5 10 15 20

**Example 1: Convert Matrix to Vector (sorted by columns) Using c() function**

The following code shows how to convert a matrix to a vector (sorted by columns) using the **c()** function:

#convert matrix to vector (sorted by columns) new_vector <- c(my_matrix) #display vector new_vector [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

**Example 2: Convert Matrix to Vector (sorted by rows) Using c() function**

The following code shows how to convert a matrix to a vector (sorted by rows) using the **c()** function:

#convert matrix to vector (sorted by rows) new_vector <- c(t(my_matrix)) #display vector new_vector [1] 1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19 5 10 15 20

**Example 3: Convert Matrix to Vector (sorted by columns) Using as.vector() function**

The following code shows how to convert a matrix to a vector (sorted by columns) using the **as.vector()** function:

#convert matrix to vector (sorted by columns) new_vector <- as.vector(my_matrix) #display vector new_vector [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

**Example 4: Convert Matrix to Vector (sorted by rows) Using as.vector() function**

The following code shows how to convert a matrix to a vector (sorted by rows) using the **as.vector()** function:

#convert matrix to vector (sorted by rows) new_vector <- as.vector(t(my_matrix)) #display vector new_vector [1] 1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19 5 10 15 20

**Additional Resources**

How to Convert a List to a Data Frame in R

How to Convert Character to Numeric in R

How to Convert Character to Factor in R