R - addition operator example
The example below shows the usage of addition(+) operator in different scenarios.
Adding a scalar
If a scalar (single element atomic vector) is added to a vector or a matrix, it is added to 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 #adding two scalars print(x1 + x2) #adding a scalar with a vector print(v1 + x2) #adding a scalar with a matrix cat("\n") print(m1 + x2)
The output of the above code will be:
[1] 15 [1] 15 25 35 [,1] [,2] [,3] [1,] 15 35 55 [2,] 25 45 65
Adding a vector
When two vectors are added, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a vector is added to a matrix, the length of longer object should be multiple of length of shorter object.
Please note that, When a vector is added to a matrix, elements are added 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) #adding a scalar (single element #atomic vector) and a vector print(x1 + v2) #adding two vectors print(v1 + v2) #adding a matrix and a vector cat("\n") print(m1 + v2)
The output of the above code will be:
[1] 15 16 17 [1] 15 26 37 [,1] [,2] [,3] [1,] 15 37 56 [2,] 26 45 67
Adding a matrix
When two matrices are added, 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) #adding a scalar (single element #atomic vector) and a matrix print(x1 + m2) #adding a vector and a matrix cat("\n") print(v1 + m2) #adding two matrices cat("\n") print(m1 + m2)
The output of the above code will be:
[,1] [,2] [,3] [1,] 11 13 15 [2,] 12 14 16 [,1] [,2] [,3] [1,] 11 33 25 [2,] 22 14 36 [,1] [,2] [,3] [1,] 11 33 55 [2,] 22 44 66
❮ R - Operators