Im trying to assign the value of -1, to every number in my vector that is inbetween 2 and 5. I thought an if - then statement would work. I am having some trouble. I dont th
I compared the solutions with microbenchmark
:
library(microbenchmark)
library(TeachingDemos)
x = runif(100000) * 1000
microbenchmark(200 %<% x %<% 500
, x > 200 & x < 500
, findInterval(x, c(200, 500)) == 1
, findInterval(x, c(200, 500)) == 1L
, times = 1000L
)
Here are the results:
expr min lq mean median uq max neval
200 %<% x %<% 500 17.089646 17.747136 20.477348 18.910708 21.302945 113.71473 1000
x > 200 & x < 500 6.774338 7.092153 8.746814 7.233512 8.284603 103.64097 1000
findInterval(x, c(200, 500)) == 1 3.578305 3.734023 5.724540 3.933615 6.777687 91.09649 1000
findInterval(x, c(200, 500)) == 1L 2.042831 2.115266 2.920081 2.227426 2.434677 85.99866 1000
You should take findInterval
.
Please consider to compare it to 1L
instead of 1
.
It is nearly twice as fast.