The Wayback Machine - https://web.archive.org/web/20240913183316/https://www.geeksforgeeks.org/create-matrix-from-vectors-in-r/
Open In App

Create Matrix from Vectors in R

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss How to convert a vector to a matrix in R Programming Language. A vector is a basic object that consists of homogeneous elements. The data type of vector can be integer, double, character, logical, complex, or raw. A vector can be created by using the c() function.

Syntax:

x <- c(val1, val2, …..)

To convert a vector to a matrix in R are the same as the arrays in C language which are used to hold multiple data values of the same type. Vectors can also be used to create matrices.

Matrices can be created with the help of Vectors by using pre-defined functions in R Programming Language. These functions take vectors as arguments along with several other arguments for matrix dimensions, etc. Functions used for Matrix creation:

  1. matrix() function
  2. cbind() function
  3. rbind() function
  4. Array() function
  5. Diag() function

matrix() function

The available data is present in single/multiple vectors, then the matrix() function can be used to create the matrix by passing the following arguments in the function to convert a vector to a matrix in R . 

Syntax:

matrix(data, nrow, ncol, byrow, dimnames)

where, 

data is the input vector which represents the elements in the matrix

 nrow specifies the number of rows to be created 

ncol specifies the number of columns to be created 

byrow specifies logical value. If TRUE, matrix will be filled by row. Default value is FALSE. 

dimnames specifies the names of rows and columns

R




# defining data in the vector
x <- c(5:16)
 
# defining row names and column names
rown <- c("row_1", "row_2", "row_3")
coln <- c("col_1", "col_2", "col_3", "col_4")
 
# creating matrix
m <- matrix(x, nrow = 3, byrow = TRUE,
            dimnames = list(rown, coln))
 
# print matrix
print(m)
 
# print class of m
class(m)


Output:

       col_1 col_2 col_3 col_4
row_1 5 6 7 8
row_2 9 10 11 12
row_3 13 14 15 16

[1] "matrix" "array"

If a matrix is to be created using data present in multiple vectors, then a vector of multiple vectors is created and passed to the matrix() function as an argument to convert a vector to a matrix in R .

R




# defining multiple vectors
x <- c(1:5)
y <- c(11:15)
z <- c(21:25)
 
# creating matrix
m <- matrix(c(x, y, z), ncol = 3)
 
# print matrix
print(m)
 
# print class of m
class(m)


Output:

     [,1] [,2] [,3]
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25

[1] "matrix" "array"

cbind() function

cbind() function in R programming is used to combine vectors, data frames, or matrices by columns and the number of rows of data sets should be equal otherwise, the output will be incomprehensible to convert a vector to a matrix in R. 

Syntax:

cbind(v1, v2, v3, ….., deparse.level)

where, 

v1, v2, v3, …. represent vectors, matrices or data frames deparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names.

R




# defining multiple vectors
x <- c(1:5)
y <- c(11:15)
z <- c(21:25)
 
# creating matrix
m <- cbind(x, y, z)
 
# print matrix
print(m)
 
# print class of m
class(m)


Output:

     x  y  z
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25

[1] "matrix" "array"

rbind() function

rbind() function in R programming is used to combine vectors, data frames or matrices by rows and number of columns of data sets should be equal otherwise, output will be insignificant to convert a vector to a matrix in R.

 Syntax:

rbind(v1, v2, v3, ….., deparse.level)

where, 

v1, v2, v3, …. represent vectors, matrices or data frames deparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names.

R




# defining multiple vectors
x <- c(1:5)
y <- c(11:15)
z <- c(21:25)
 
# creating matrix
n <- rbind(x, y, z)
 
# print matrix
print(n)
 
# print class of m
class(n)


Output:

  [,1] [,2] [,3] [,4] [,5]
x 1 2 3 4 5
y 11 12 13 14 15
z 21 22 23 24 25

[1] "matrix" "array"

Array() function

The array() function can be used to create a matrix from vectors, as well as higher dimensional arrays to convert a vector to a matrix in R.

 Syntax:

array(data, dim)

where, 

  • data: The input vector or data that will be used to create the array.
  • dim: The dimension of the array. It can be a vector of integers indicating the number of elements in each dimension.

R




# defining multiple vectors
x <- c(1:5)
y <- c(11:15)
z <- c(21:25)
 
# Using the array() function
n=array(c(x, y, z), dim = c(5, 3))
 
# print class of m
class(n)


Output:

      [,1] [,2] [,3]
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25

[1] "matrix" "array"

Diag() function:

The diag() function can be used to create to convert a vector to a matrix in R.

Syntax:

diag(x, nrow, ncol)

where, 

  • x: a vector that will be placed on the diagonal of the resulting matrix. If x is a scalar, it will be repeated to create a vector of the required length.
  • nrow: the number of rows in the resulting matrix.
  • ncol: the number of columns in the resulting matrix.

R




x <- c(1:5)
y <- c(11:15)
z <- c(21:25)
 
n=diag(c(x, y, z))
 
print(n)
 
class(n)


Output:

        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 11 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 13 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 14 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 15 0 0 0 0 0
[11,] 0 0 0 0 0 0 0 0 0 0 21 0 0 0 0
[12,] 0 0 0 0 0 0 0 0 0 0 0 22 0 0 0
[13,] 0 0 0 0 0 0 0 0 0 0 0 0 23 0 0
[14,] 0 0 0 0 0 0 0 0 0 0 0 0 0 24 0
[15,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25

[1] "matrix" "array"


Similar Reads

Create a matrix from a list of vectors using R
In this article, we are going to learn how we can convert the list of vectors into a matrix using R Programming Language. If you want to convert simple vectors to a matrix not the list of vectors. The data type of vector can be integer, double, character, logical, complex, or raw. A vector can be created by using the c() function. To create a vecto
6 min read
Combine Vectors, Matrix or Data Frames by Columns in R Language - cbind() Function
cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns. Syntax: cbind(x1, x2, ..., deparse.level = 1) Parameters: x1, x2: vector, matrix, data frames deparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example 1: # R program to illustrate # cbind
2 min read
Combine Vectors, Matrix or Data Frames by Rows in R Language - rbind() Function
In this article, we will discuss how we Combine Vectors, Matrices, or Data Frames by Rows in R Programming Language using rbind function. What is rbind function?The rbind function combines or concatenates data frames or matrices by rows. the rbind stands for row binds it shows that it appends rows of one object to another. Syntax: rbind(x1, x2, ...
3 min read
Operations on Vectors in R
Vectors are the most basic data types in R. Even a single object created is also stored in the form of a vector. Vectors are nothing but arrays as defined in other languages. Vectors contain a sequence of homogeneous types of data. If mixed values are given then it auto converts the data according to the precedence. There are various operations tha
4 min read
List of Vectors in R
Vectors are a sequence of elements belonging to the same data type. A list in R, however, comprises of elements, vectors, variables or lists which may belong to different data types. In this article, we will study how to create a list consisting of vectors as elements and how to access, append and delete these vectors to lists. list() function in R
6 min read
Compute the beta value of Non-Negative Numeric Vectors in R Programming - beta() Function
beta() function in R Language is used to return the beta value computed using the beta function. The beta function is also known as Euler's integral of the first kind. Syntax: beta(a, b) Parameters: a, b: non-negative numeric vectors Example 1: # R program to illustrate # beta function # Calling the beta() function beta(1, 2) beta(2, 2) beta(3, 5)
1 min read
Get the natural logarithm of the beta value of Non-Negative numeric vectors in R Language - lbeta() Function
lbeta() function in R Language is used to return the natural logarithm of the beta function. The beta function is also known as Euler's integral of the first kind. Syntax: lbeta(a, b) Parameters: a, b: non-negative numeric vectors Example 1: # R program to illustrate # lbeta function # Calling the lbeta() function lbeta(1, 2) lbeta(2, 2) lbeta(3, 5
1 min read
Compute the Covariance between Two Vectors in R Programming - cov() Function
cov() function in R Language is used to measure the covariance between two vectors. Syntax: cov(x, y, method) Parameters: x, y: Data vectors method: Type of method to be used Example 1: # Data vectors x &lt;- c(1, 3, 5, 10) y &lt;- c(2, 4, 6, 20) # Print covariance using Pearson method print(cov(x, y, method = &quot;pearson&quot;)) Output: [1] 30.6
1 min read
Compute the Correlation Coefficient Value between Two Vectors in R Programming - cor() Function
cor() function in R Language is used to measure the correlation coefficient value between two vectors. Syntax: cor(x, y, method) Parameters: x, y: Data vectors method: Type of method to be used Example 1: # Data vectors x &lt;- c(1, 3, 5, 10) y &lt;- c(2, 4, 6, 20) # Print covariance using Pearson method print(cor(x, y, method = &quot;pearson&quot;
1 min read
Creating a Data Frame from Vectors in R Programming
A vector can be defined as the sequence of data with the same datatype. In R, a vector can be created using c() function. R vectors are used to hold multiple data values of the same datatype and are similar to arrays in C language. Data frame is a 2 dimensional table structure which is used to hold the values. In the data frame, each column contain
5 min read
Generating sequenced Vectors in R Programming - sequence() Function
sequence() function in R Language is used to create a vector of sequenced elements. It creates vectors with specified length, and specified differences between elements. It is similar to seq() function. Syntax: sequence(x) Parameters: x: Maximum element of vector Example 1: # R program to create sequence of vectors # Calling sequence() function seq
1 min read
Generate Color Vectors of desired Length in R Programming - rainbow() Function
rainbow() function in R Language is a built in color palettes which can be used to quickly generate color vectors of desired length taken as the parameter and returns the hexadecimal code of the colours available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and
1 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 &lt;- c(2, 9, 5, 7, 1, 8) # Second example vector x2 &lt;- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Assigning Vectors in R Programming
Vectors are one of the most basic data structure in R. They contain data of same type. Vectors in R is equivalent to arrays in other programming languages. In R, array is a vector of one or more dimensions and every single object created is stored in the form of a vector. The members of a vector are termed as components . Assigning of Vectors There
5 min read
Types of Vectors in R Programming
Vectors in R programming are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’. Vectors are the most basic data types in R. Even a single object created is also stored in the form of a vector. Vectors are
5 min read
Dot Product of Vectors in R Programming
In mathematics, the dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors. Given that, [Tex]A = a_1i + a_2j + a_3k [/Tex] and, [Tex]B = b_1i + b_2j + b_3k [/Tex] where
3 min read
Cross Product of Vectors in R Programming
In mathematics, the cross product or also known as the vector product is a binary operation on two vectors in three-dimensional space and is denoted by the symbol 'X'. Given two linearly independent vectors a and b, the cross product, a × b is a vector that is perpendicular to both a and b and thus normal to the plane containing them. Let we have g
4 min read
Convert an Excel column into a list of vectors in R
In this article, we will be discussing the different approaches to convert the Excel columns to vector in the R Programming language. File in use: Method 1: Using $-Operator with the column name In this method, we will be simply using the $-operator with the column name and the name of the data read from the excel file. Here, the name of the column
2 min read
How to Fix in R: $ operator is invalid for atomic vectors
In this article, we are going to see how to fix $ operator is invalid for atomic vectors in the R programming language. The error that one may face in R is: $ operator is invalid for atomic vectors Such an error is produced by the R compiler when we try to get an element of an atomic vector by using the $ operator. An atomic vector is simply a 1-di
4 min read
Getting and Setting Length of the Vectors in R Programming - length() Function: Title change need
In R, the length of a vector is the number of elements it contains. Vectors can be of different types, such as numeric, character, or logical, and the length() function is a versatile way to determine the number of elements in a vector. length() function in R Programming Language is used to get or set the length of a vector (list) or other objects.
4 min read
Append Operation on Vectors in R Programming
In this article, let us discuss different methods to concatenate/append values to a vector in R Programming Language. Append method in RVectors in the R Programming Language is a basic objects consisting of sequences of homogeneous elements. vector can be integer, logical, double, character, complex, or raw. Values can be appended/concatenated in a
3 min read
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.  Creating a vectorA vector is a basic data structure that
5 min read
Calculate the outer product of two vectors using R
In this article, we will explore different ways to Calculate the outer product of two vectors using R Programming Language. What is the outer product of two vectorsthe outer product of two vectors is a matrix where each element is the product of a corresponding element from the first vector with a corresponding element from the second vector. The r
3 min read
How to Compute the Angle Between Vectors Using Python
In mathematics and computer science calculating the angle between the vectors is a fundamental operation used in the various applications such as the machine learning computer graphics and physics simulations. The angle between the two vectors u and v can be determined using the principles from the linear algebra and trigonometry. Let's explore dif
4 min read
Subtracting similarly named elements in a list of vectors in R
When working with vectors in R, you might encounter a situation where you need to perform operations on elements with similar names across different vectors within a list. One common operation is subtraction. This article will guide you through the process of subtracting similarly named elements in a list of vectors in the R Programming Language. I
3 min read
Why Can't R's ifelse Statements Return Vectors?
In R, the ifelse() function is designed to perform element-wise conditional operations on vectors. However, a common point of confusion arises when trying to use ifelse() to return vectors (or lists) as elements in its output. The function's behavior and underlying design principles explain why ifelse() doesn't return vectors as expected in the R P
4 min read
How Can I Convert a List of Character Vectors to a Single Vector in R?
In R Language lists are a flexible data structure that can contain elements of different types, including vectors. When working with lists of character vectors, you might want to combine them into a single vector for easier manipulation or analysis. This can be done using various built-in functions like unlist() or using the purrr package for more
3 min read
How to Convert Sparse Matrix to Dense Matrix in R?
R is a programming language used for performing statistical computation and graphical purposes. It is currently supported and backed by the R Core Team and the R Foundation for Statistical Computing. For data analysis and the creation of statistical software, R Programming Language is used by statisticians, bioinformaticians, and data miners. The p
2 min read
Check if the Object is a Matrix in R Programming - is.matrix() Function
is.matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE. Syntax: is.matrix(x) Parameters: x: specified matrix Example 1: # R program to illustrate # is.matrix function # Specifying some different types of arrays A &lt;- matrix(c(1:5)) B &lt;- matrix(c(1:12), nrow = 4, byrow = TRUE)
1 min read
Convert a Data Frame into a Numeric Matrix in R Programming - data.matrix() Function
data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix. Syntax: data.matrix(df) Parameters: df: Data frame to be converted. Example 1: # R program to convert a data frame # into a numeric matrix # Creating a dataframe df1 = data.frame( &quot;Na
2 min read
Practice Tags :