# Convert Vector to Matrix in R (Example)

In this article you’ll learn how to **switch from vector to matrix class** in R programming.

The content of the page looks as follows:

With that, let’s get started.

## Creation of Example Data

As a first step, we’ll have to create some example data:

vec <- 1:15 # Create example vector vec # Print example vector # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |

vec <- 1:15 # Create example vector vec # Print example vector # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

The previous output of the RStudio console shows that our example data is a vector consisting of 15 numeric elements.

## Example: Converting Vector to Matrix

In this example, I’ll show how to create a matrix based on our example vector (or array) using the matrix function in R.

Have a look at the following R code:

mat <- matrix(vec, ncol = 3) # Convert vector to matrix mat # Print matrix # [,1] [,2] [,3] # [1,] 1 6 11 # [2,] 2 7 12 # [3,] 3 8 13 # [4,] 4 9 14 # [5,] 5 10 15 |

mat <- matrix(vec, ncol = 3) # Convert vector to matrix mat # Print matrix # [,1] [,2] [,3] # [1,] 1 6 11 # [2,] 2 7 12 # [3,] 3 8 13 # [4,] 4 9 14 # [5,] 5 10 15

As you can see based on the previous output of the RStudio console, we have created a numeric matrix containing of five rows and three columns.

## Video & Further Resources

I have recently released a video on my YouTube channel, which illustrates the R syntax of this page. You can find the video tutorial below:

*The YouTube video will be added soon.*

In addition, you might have a look at some of the other tutorials of this homepage:

- Convert Factor to Character Class
- Multiply Rows of Matrix by Vector in R
- Convert Data Frame Row to Vector
- Convert Matrix to Vector in R
- Introduction to R Programming

In summary: In this R post you learned how to **convert a vector to a matrix**. Let me know in the comments below, if you have additional comments and/or questions.

**5**/

**5**(

**1**vote )

### Subscribe to my free statistics newsletter: