R Tutorial R Charts & Graphs R Statistics R References

R - modulo operator example



The example below shows the usage of modulo(%%) operator in different scenarios.

Remainder 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

#remainder when dividing two scalars 
#(single element atomic vectors) 
print(x1 %% x2)
#remainder when dividing a vector by a scalar
print(v1 %% x2)
#remainder when dividing a matrix by a scalar
cat("\n")
print(m1 %% x2)

The output of the above code will be:

[1] 3
[1] 3 6 2

     [,1] [,2] [,3]
[1,]    3    2    1
[2,]    6    5    4

Remainder 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)

#remainder when dividing a scalar (single 
#element atomic vector) by a vector
print(x1 %% v2)
#remainder when dividing two vectors
print(v1 %% v2)
#remainder when dividing a matrix by a vector
cat("\n")
print(m1 %% v2)

The output of the above code will be:

[1] 0 4 3
[1] 0 2 2

     [,1] [,2] [,3]
[1,]    0    2    2
[2,]    2    0    4

Remainder 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)

#remainder when dividing a scalar (single 
#element atomic vector) by a matrix
print(x1 %% m2)
#remainder when dividing a vector by a matrix
cat("\n")
print(v1 %% m2)
#remainder when dividing two matrices
cat("\n")
print(m1 %% m2)

The output of the above code will be:

     [,1] [,2] [,3]
[1,]    0    3    1
[2,]    4    2    0

     [,1] [,2] [,3]
[1,]    0    2    2
[2,]    2    2    0

     [,1] [,2] [,3]
[1,]    0    2    5
[2,]    2    0    0

❮ R - Operators