Subtract Constant Vector from Each Row of Matrix in R (Example Code)

In this article you’ll learn how to subtract or add a vector from each row of a matrix object in R programming.

Constructing Exemplifying Data

data(iris)                            # Load and prepare example data
iris_mat <- iris[1:5, 1:4]
iris_mat                              # Display example data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1          5.1         3.5          1.4         0.2
# 2          4.9         3.0          1.4         0.2
# 3          4.7         3.2          1.3         0.2
# 4          4.6         3.1          1.5         0.2
# 5          5.0         3.6          1.4         0.2
example_vector <- 10:13               # Example vector in R
example_vector                        # Display example vector
# [1] 10 11 12 13

Example: Apply sweep() Function to Subtract Vector from Matrix Rows

sweep(iris_mat, 2, example_vector)    # Using sweep() function
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1         -4.9        -7.5        -10.6       -12.8
# 2         -5.1        -8.0        -10.6       -12.8
# 3         -5.3        -7.8        -10.7       -12.8
# 4         -5.4        -7.9        -10.5       -12.8
# 5         -5.0        -7.4        -10.6       -12.8

Further Resources & Related Tutorials

Here, you can find some additional resources that are similar to the topic of this page:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top