I'm late to the party on this, but I do have a similar solution which seems to run pretty fast. It is similar to the other options, but uses the trunc
function.
x<- c(10, 15, 20, 27, 30, 34)
trunc(x / 10) * 10
#> [1] 10 10 20 20 30 30
identical(x %/% 10 * 10, floor(x/10) * 10)
#> [1] TRUE
identical(trunc(x / 10) * 10, floor(x/10) * 10)
#> [1] TRUE
Created on 2019-01-09 by the reprex package (v0.2.1)
I have inflated the size of the x
vector and run all three with microbenchmark
. The trunc
method is fastest on this data.
set.seed(42)
x <- sample(x, size = 10000000, replace = TRUE)
library(microbenchmark)
microbenchmark(trunc(x / 10) * 10,
floor(x / 10) * 10,
x%/%10*10)
#> Unit: milliseconds
#> expr min lq mean median uq
#> trunc(x/10) * 10 55.89856 58.57783 66.08508 65.62727 71.74459
#> floor(x/10) * 10 95.50139 99.18817 108.17770 108.10694 113.86548
#> x%/%10 * 10 143.65839 150.77401 157.42086 158.56745 161.84987
#> max neval
#> 95.49897 100
#> 147.47947 100
#> 188.56060 100
Created on 2019-01-09 by the reprex package (v0.2.1)