# How to Convert R Matrix to Vector

To convert Vector to Matrix in the R language, use the matrix() function. The vector can hold multiple elements, but all the elements are of the same data type. R Matrix is a vector with attributes of a dimension and optionally, dimension names attached to a Vector.

## Convert R Matrix to Vector

To convert Matrix to Vector in R, use the c() function. The c() function combine values into a Vector or List. The c() is an inbuilt generic function that combines its arguments to form a vector. All arguments are coerced to a standard type which is the type of the returned value and all attributes except names are removed.

### Example

To create a matrix in R, use the matrix() function.

``````mat <- matrix(1:12, nrow = 4)
mat``````

#### Output

``````     [,1] [,2] [,3]
[1,]  1    5     9
[2,]  2    6    10
[3,]  3    7    11
[4,]  4    8    12``````

You can see that we created a 4 X 3 matrix.

To convert this matrix to a vector, use the c() function and pass this matrix in the argument.

``````mat <- matrix(1:12, nrow = 4)
mat
rv <- c(mat)
rv``````

#### Output

``````     [,1] [,2] [,3]
[1,]  1    5    9
[2,]  2    6   10
[3,]  3    7   11
[4,]  4    8   12

[1] 1 2 3 4 5 6 7 8 9 10 11 12``````

That is it. We get the vector from the matrix. The c() function converts a matrix into a one-dimensional vector.

## Converting Matrix to Vector Using as.vector() Function

The as.vector() function converts a distributed matrix into a non-distributed vector. The as.vector() takes a matrix as an argument and returns the vector.

### Syntax

``as.vector(x, mode = "any", proc.dest = "all")``

### Parameters

x: numeric distributed matrix.

mode: A character string giving an atomic mode or “list“, or (except for ‘vector’) “any”.

proc.dest: destination process for storing the matrix.

### Example

``````mat <- matrix(1:12, nrow = 4)
mat
cat("After converting from matrix to vector", "\n")
rv <- as.vector(mat)
rv``````

#### Output

``````     [,1] [,2] [,3]
[1,]  1    5    9
[2,]  2    6   10
[3,]  3    7   11
[4,]  4    8   12
After converting from matrix to vector
[1] 1 2 3 4 5 6 7 8 9 10 11 12``````

You can see that we get the vector using as.vector() function. The as.vector() method in R Language is used to convert an object into a vector. That is it for this conversion tutorial.

Categories R