Convert Matrix to Vector in R (3 Examples)
In this article, I’ll illustrate how to switch from matrix to vector format in the R programming language.
The article consists of three examples for the conversion of matrices. To be more precise, the article contains these content blocks:
Here’s how to do it:
Introducing Exemplifying Data
First, we have to construct some example data:
my_mat <- matrix(11:30, nrow = 4) # Create example matrix my_mat # Print example matrix # [,1] [,2] [,3] [,4] [,5] # [1,] 11 15 19 23 27 # [2,] 12 16 20 24 28 # [3,] 13 17 21 25 29 # [4,] 14 18 22 26 30
The previous RStudio console output shows the structure of our example data – It’s a matrix with four rows and five columns. All values in the matrix are numeric.
Example 1: Converting Matrix to Vector Using c() Function
In Example 1, I’ll show how to convert a matrix to a one-dimensional vector using the c() function:
c(my_mat) # Applying c function # 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
As you can see, the output of the previous R code is a simple vector ranging from 11 to 30.
Example 2: Converting Matrix to Vector Using as.vector() Function
Alternatively to the c() function (as shown in Example 1), we can also use the as.vector function:
as.vector(my_mat) # Applying as.vector function # 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
The result is exactly the same as in Example 1.
Example 3: Converting Matrix to Vector by Rows Using t() & as.vector() Functions
So far, we have converted our matrix by columns. However, it is also possible to convert a matrix to a one-dimensional vector by rows.
The following R programming code explains how to do this in R by using the t and as.vector functions:
as.vector(t(my_mat)) # Applying t & as.vector functions # 11 15 19 23 27 12 16 20 24 28 13 17 21 25 29 14 18 22 26 30
The previous output is containing row No. 1 first, row No. 2 second, and so on…
Video, Further Resources & Summary
Would you like to know more about matrices and arrays? Then you could watch the following video of my YouTube channel. I explain the contents of the present tutorial in the video.
In addition, you might want to read the related articles of my homepage. I have published several articles about related topics such as matrices, lists, data conversion, and vectors.
- Convert Named Vector to Data Frame in R
- Multiply Rows of Matrix by Vector in R
- Convert Data Frame Row to Vector in R
- Convert Vector to List in R
- Introduction to R Programming
You learned in this article how to convert and vectorize a matrix to a vector object in R programming. Let me know in the comments, in case you have further questions.