%%, %/% operators

Compute the modulo (%%) or use integer division (%/%).
x %% y (modulo)
  • x – A numerical value or numerical vector.
  • y – A numerical value or numerical vector.
x %/% y (numerical division)
  • x – A numerical value or numerical vector.
  • y – A numerical value or numerical vector.

Example. Below are several simple examples, followed by an example shown in the txtProgressBar, setTxtProgressBar post. In that later example, the modulo was used in the last loop so that setTxtProgressBar was only run once every 1000 iterations, which sped up the loop.
> 7 / 2
[1] 3.5
> 
> 7 %% 2
[1] 1
> 
> 7 %/% 2
[1] 3
> 
> 
> 11.8 %% 5
[1] 1.8
> 
> 11.8 %/% 5
[1] 2
> 
> x <- 11.8
> y <- 5
> (x %% y) + y*(x %/% y)
[1] 11.8
> 
> 
> 13 %% 1:5
[1] 0 1 1 1 3
> 
> 
> # May produce different results:
> 1 %% 0.2
[1] 0
> 
> 1 %/% 0.2
[1] 5
> 
> 
> # To access the help file for %% and %/%,
> # use acute accents around %%
> ?`%%`
> 
> 
> #=====> See txtProgressBar Post <=====#
> SEQ  <- seq(1,100000)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+ }
> Sys.time() - TIME
Time difference of 3.872829 secs
> 
> pb   <- txtProgressBar(1, 100000, style=3)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+   setTxtProgressBar(pb, i)
+ }
  |===================================================| 100%
> Sys.time() - TIME
Time difference of 8.296607 secs
> 
> pb   <- txtProgressBar(1, 100000, style=3)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+   if(i %% 1000 == 0){
+     setTxtProgressBar(pb, i)
+   }
+ }
  |===================================================| 100%
> Sys.time() - TIME
Time difference of 4.218381 secs

Leave a Reply