R - subtraction operator example
The example below shows the usage of subtraction(-) operator in different scenarios.
Subtracting a scalar
If a scalar (single element atomic vector) is subtracted to a vector or a matrix, it is subtracted from each element of the vector or matrix.
#first operand x1 <- 10 v1 <- c(10, 20, 30) m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2) #second operand x2 <- 5 #subtracting a scalar from another print(x1 - x2) #subtracting a scalar from a vector print(v1 - x2) #subtracting a scalar from a matrix cat("\n") print(m1 - x2)
The output of the above code will be:
[1] 5 [1] 5 15 25 [,1] [,2] [,3] [1,] 5 25 45 [2,] 15 35 55
Subtracting a vector
When a vector is subtracted from another, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a vector is subtracted from a matrix, the length of longer object should be multiple of length of shorter object.
Please note that, When a vector is subtracted from a matrix, elements are subtracted column-wise.
#first operand x1 <- 10 v1 <- c(10, 20, 30) m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2) #second operand v2 <- c(5, 6, 7) #subtracting a vector from a scalar #(single element atomic vector) print(x1 - v2) #subtracting a vector from another print(v1 - v2) #subtracting a vector from a matrix cat("\n") print(m1 - v2)
The output of the above code will be:
[1] 5 4 3 [1] 5 14 23 [,1] [,2] [,3] [1,] 5 23 44 [2,] 14 35 53
Subtracting a matrix
When a matrix is subtracted from another, their dimension should be same or dimension of bigger matrix should be multiple of dimension of smaller matrix.
#first operand x1 <- 10 v1 <- c(10, 20, 30) m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2) #second operand m2 <- matrix(c(1, 2, 3, 4, 5, 6), nrow=2) #subtracting a matrix from a scalar #(single element atomic vector) print(x1 - m2) #subtracting a matrix from a vector cat("\n") print(v1 - m2) #subtracting a matrix from another cat("\n") print(m1 - m2)
The output of the above code will be:
[,1] [,2] [,3] [1,] 9 7 5 [2,] 8 6 4 [,1] [,2] [,3] [1,] 9 27 15 [2,] 18 6 24 [,1] [,2] [,3] [1,] 9 27 45 [2,] 18 36 54
❮ R - Operators