R - floor division operator example
The example below show the usage of floor division(%/%) operator in different scenarios.
Quotient when dividing by a scalar
When used a vector or a matrix, it acts on each element of it.
#first operand x1 <- 10 v1 <- c(10, 20, 30) m1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow=2) #second operand x2 <- 7 #quotient when dividing two scalars #(single element atomic vectors) print(x1 %/% x2) #quotient when dividing a vector by a scalar print(v1 %/% x2) #quotient when dividing a matrix by a scalar cat("\n") print(m1 %/% x2)
The output of the above code will be:
[1] 1 [1] 1 2 4 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8
Quotient when 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) #quotient when dividing a scalar (single #element atomic vector) by a vector print(x1 %/% v2) #quotient when dividing two vectors print(v1 %/% v2) #quotient when dividing a matrix by a vector cat("\n") print(m1 %/% v2)
The output of the above code will be:
[1] 2 1 1 [1] 2 3 4 [,1] [,2] [,3] [1,] 2 4 8 [2,] 3 8 8
Quotient when 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(5, 6, 7, 8, 9, 10), nrow=2) #quotient when dividing a scalar (single #element atomic vector) by a matrix print(x1 %/% m2) #quotient when dividing a vector by a matrix cat("\n") print(v1 %/% m2) #quotient when dividing two matrices cat("\n") print(m1 %/% m2)
The output of the above code will be:
[,1] [,2] [,3] [1,] 2 1 1 [2,] 1 1 1 [,1] [,2] [,3] [1,] 2 4 2 [2,] 3 1 3 [,1] [,2] [,3] [1,] 2 4 5 [2,] 3 5 6
❮ R - Operators