Quickest way to find closest elements in an array in R
问题 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-loop, but there must be a better way to do it: Xtimes <- c(1,5,8,10,15,19,23,34,45,51,55,57,78,120) Ytimes <- seq(0,120,length.out = 1000) YmatchIndex = array(0,length(Xtimes)) for (i in 1:length(Xtimes)) { YmatchIndex[i] = which.min(abs(Ytimes - Xtimes[i])) } print(Ytimes[YmatchIndex]) 回答1: R is vectorized, so skip the for loop