R - division operator example
The example below shows the usage of division(/) operator in different scenarios.
Dividing by a scalar
If a vector or a matrix is divided by a scalar (single element atomic vector), then each element of it is divided by the given scalar.
#first operand x1 <- 10 v1 <- c(10, 20, 30) m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2) #second operand x2 <- 5 #dividing two scalars print(x1 / x2) #dividing a vector by a scalar print(v1 / x2) #dividing a matrix by a scalar cat("\n") print(m1 / x2)
The output of the above code will be:
[1] 2 [1] 2 4 6 [,1] [,2] [,3] [1,] 2 6 10 [2,] 4 8 12
Dividing by a vector
When a vector is divided by another vector, their length should be same or length of longer vector should be multiple of length of shorter vector. Similarly, when a matrix is divided by a vector, the length of longer object should be multiple of length of shorter object.
Please note that, When a matrix is divided by a vector, elements are divided 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) #dividing a scalar (single element #atomic vector) by a vector print(x1 / v2) #dividing two vectors print(v1 / v2) #dividing a matrix by a vector cat("\n") print(m1 / v2)
The output of the above code will be:
[1] 2.000000 1.666667 1.428571 [1] 2.000000 3.333333 4.285714 [,1] [,2] [,3] [1,] 2.000000 4.285714 8.333333 [2,] 3.333333 8.000000 8.571429
Dividing by a matrix
When a matrix is divided by another matrix, 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) #dividing a scalar (single element #atomic vector) by a matrix print(x1 / m2) #dividing a vector by a matrix cat("\n") print(v1 / m2) #dividing two matrices cat("\n") print(m1 / m2)
The output of the above code will be:
[,1] [,2] [,3] [1,] 10 3.333333 2.000000 [2,] 5 2.500000 1.666667 [,1] [,2] [,3] [1,] 10 10.0 4 [2,] 10 2.5 5 [,1] [,2] [,3] [1,] 10 10 10 [2,] 10 10 10
❮ R - Operators