I would like find the fastes way in R to indentify indexes of elements in Ytimes array which are closest to given Xtimes values.
So far I have been using a simple for-lo
R
is vectorized, so skip the for
loop. This saves time in scripting and computation. Simply replace the for
loop with an apply
function. Since we're returning a 1D vector, we use sapply
.
YmatchIndex <- sapply(Xtimes, function(x){which.min(abs(Ytimes - x))})
Proof that apply
is faster:
library(microbenchmark)
library(ggplot2)
# set up data
Xtimes <- c(1,5,8,10,15,19,23,34,45,51,55,57,78,120)
Ytimes <- seq(0,120,length.out = 1000)
# time it
mbm <- microbenchmark(
for_loop = for (i in 1:length(Xtimes)) {
YmatchIndex[i] = which.min(abs(Ytimes - Xtimes[i]))
},
apply = sapply(Xtimes, function(x){which.min(abs(Ytimes - x))}),
times = 100
)
# plot
autoplot(mbm)
See ?apply for more
.