Divide Each Row of Matrix by Vector Elements in R
Last Updated :
17 May, 2021
In this article, we will discuss how to divide each row of the matrix by vector elements in R Programming Language.
Method 1: Using standard division
Initially, the transpose of the matrix is computed, to interchange the rows and columns. Initially, if the dimensions of the matrix were n * m , transpose converts the dimensions to m * n. The transpose of the matrix needs to be computed because the boolean division operator "/" is applied column-wise, and we need to compute row-wise division. The division operation is then applied using transpose matrix as one operand and vector as the other. The transpose of this result is then taken, to preserve the order of rows and columns again.
Syntax:
t(transpose_matrix/vector)
Example:
R
# creating matrix
matrix <- matrix(1:12,ncol=3)
print ("Original Matrix")
print (matrix)
# creating vector
vec <- c(1:3)
# transpose matrix
trans_mat <- t(matrix)
# computing division
div <- t(trans_mat/vec)
print ("Division matrix")
print (div)
Output
[1] "Original Matrix"
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
[1] "Division matrix"
[,1] [,2] [,3]
[1,] 1 2.5 3.000000
[2,] 2 3.0 3.333333
[3,] 3 3.5 3.666667
[4,] 4 4.0 4.000000
Method 2: Using sweep() method
This method in R language returns an array obtained from an input array by sweeping out a summary statistic. The method is used to compute arithmetic operations on the data frame over the chosen axis. For, row-wise operation the chosen axis is 2 and the operand becomes the row of the data frame. The result has to be stored in another variable. The time incurred in this operation is equivalent to the number of rows in the data frame. The data type of the resultant column is the largest compatible data type.
Syntax: sweep (df , axis, vec, op)
Parameter :
- df - DataFrame
- axis - To compute it row-wise, use axis = 1 and for column-wise, use axis = 2
- vec - The vector to apply on the data frame
- op - The operator to apply
Example:
R
# creating matrix
matrix <- matrix(1:12,ncol=3)
print ("Original Matrix")
print (matrix)
# creating vector
vec <- c(1:3)
# computing division
div <- sweep(matrix, 2, vec, "/")
print ("Division matrix")
print (div)
Output
[1] "Original Matrix"
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
[1] "Division matrix"
[,1] [,2] [,3]
[1,] 1 2.5 3.000000
[2,] 2 3.0 3.333333
[3,] 3 3.5 3.666667
[4,] 4 4.0 4.000000
Method 3 : Using rep() method
rep(x) method in R is used to replicate the values in vector x. It takes as an argument the "each" argument, where each element is repeated each number of times. The rep() function replicates numeric values, or text, or the values of a vector for a specific number of times.
Syntax: rep ( vec, each = )
Parameter :
- vec : The vector whose value is replicated.
- each : non-negative integer. Other inputs will be coerced to an integer or double vector and the first element taken.
The idea of the application of rep() method here is to create a replication of the vector and stack it together, to create a number of copies equivalent to the number of rows. This is followed by the division of the involved matrices.
Example:
R
# creating matrix
matrix <- matrix(1:16,ncol=2)
print ("Original Matrix")
print (matrix)
# creating vector
vec <- c(1:2)
# calculating rows
rows <- nrow(matrix)
# computing division
div <- matrix / rep(vec, each = rows)
print ("Division matrix")
print (div)
Output
[1] "Original Matrix"
[,1] [,2]
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
[1] "Division matrix"
[,1] [,2]
[1,] 1 4.5
[2,] 2 5.0
[3,] 3 5.5
[4,] 4 6.0
[5,] 5 6.5
[6,] 6 7.0
[7,] 7 7.5
[8,] 8 8.0
Method 4: Using apply() method
The apply() method is a form of collection method, which is used to apply transformations over the entire specified object. apply() method takes as input the data frame or matrix and gives output in vector, list, or array.
Syntax: apply(matrix , axis , FUN)
Parameter :
- matrix : an array or matrix
- axis : indicator of the axis over which transformation is applied
- axis =1 : row-wise manipulation
- axis =2 : column-wise manipulation
- axis=c(1,2) : the manipulation is performed on rows and columns
- FUN: tells which function to apply.
The transpose of the result has to be computed to preserve the order after the application of the apply() method because the apply() method returns the transposed matrix.
Example:
R
# creating matrix
matrix <- matrix(1:16,ncol=2)
print ("Original Matrix")
print (matrix)
# creating vector
vec <- c(1:2)
# calculating rows
rows <- nrow(matrix)
# computing division
div <- t(apply(matrix, 1, "/", vec))
print ("Division matrix")
print (div)
Output
[1] "Original Matrix"
[,1] [,2]
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
[1] "Division matrix"
[,1] [,2]
[1,] 1 4.5
[2,] 2 5.0
[3,] 3 5.5
[4,] 4 6.0
[5,] 5 6.5
[6,] 6 7.0
[7,] 7 7.5
[8,] 8 8.0
Method 5 : Using %*% operator
The %*% operator is a special kind of multiplication operator, defined for the purpose of matrix multiplication. This operator is used to multiply a matrix with its transpose. Initially, the diagonal matrix is computed for the specified vector, using the diag() function in R. It takes as argument the inverse of the vector, and then this matrix is multiplied with the original matrix to produce the division. This eliminates the need of explicit division, because the inverse is already taken into account.
Syntax: diag( x )
Parameter :
x: vector to be present as the diagonal elements.
Example:
R
# creating matrix
matrix <- matrix(1:16,ncol=2)
print ("Original Matrix")
print (matrix)
# creating vector
vec <- c(1:2)
# calculating rows
rows <- nrow(matrix)
# computing division
div <- matrix %*% diag(1 / vec)
print ("Division matrix")
print (div)
Output
[1] "Original Matrix"
[,1] [,2]
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
[1] "Division matrix"
[,1] [,2]
[1,] 1 4.5
[2,] 2 5.0
[3,] 3 5.5
[4,] 4 6.0
[5,] 5 6.5
[6,] 6 7.0
[7,] 7 7.5
[8,] 8 8.0
Similar Reads
Divide each dataframe row by vector in R
In this article, we will discuss how to divide each dataframe row by vector in R Programming Language. Method 1 : Using mapply() method The mapply() method can be used to apply a FUN to the dataframe or a matrix, to modify the data. The function specified as the first argument may be any boolean ope
3 min read
How to Set the Diagonal Elements of a Matrix to 1 in R?
In this article, we will discuss how to set the diagonal elements of a Matrix to 1 in R Programming Language. Matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. In R program
2 min read
Find product of vector elements in R
In this article, we will see how to find the product of vector elements in R programming language. Method 1: Using iteration Approach Create dataframeIterate through the vectorMultiply elements as we goDisplay product The following code snippet indicates the application of for loop over decimal poin
2 min read
How to convert matrix to list of vectors in R ?
In this article, we will learn how to convert a matrix into a list of vectors in R Programming Language. Converting matrix into a list of vectors by Columns Method 1: Using as.list() function To convert columns of the matrix into a list of vectors, we first need to convert the matrix to a dataframe
4 min read
Convert Matrix to Vector in R
In this article, we are going to convert the given matrix into the vector in R programming language. Conversion of the matrix to vector by rowMethod 1: Using c() function Simply passing the name of the matrix will do the job. Syntax: c(matrix_name) Where matrix_name is the name of the input matrix E
3 min read
How to Convert matrix to a list of column vectors in R ?
In this article, we will discuss how to convert a given matrix to a list of column vectors in R Programming Language. To do this we will take every column of the matrix and store that column in a list and at last print the list. It can be done in these ways: Using the split() functionUsing list() wi
3 min read
Set Diagonal of a Matrix to zero in R
Matrices are fundamental data structures in R that allow you to store and manipulate two-dimensional data. If you want to set diagonal element of matrix to zero in R programming language then you have to follow these steps to attain it. Concepts Related to the Topic:Matrix Diagonal: In NxN matrix, t
3 min read
Subset DataFrame and Matrix by Row Names in R
In this article, we are going to see how to evaluate subset dataframe and matrices by row name. Method 1: Subset dataframe by row names The rownames(df) method in R is used to set the names for rows of the data frame. A vector of the required row names is specified. The %in% operator in R is used t
2 min read
Extract every Nth element of a vector in R
In this article, we will see how to extract every Nth element from a vector in R Programming Language. Method 1: Using iteration An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and as soon as the nth el
3 min read
Multiply Matrix by Vector in R
A matrix is a 2-dimensional structure whereas a vector is a one-dimensional structure. In this article, we are going to multiply the given matrix by the given vector using R Programming Language. Multiplication between the two occurs when vector elements are multiplied with matrix elements column-wi
2 min read