在R中找到数组中最接近元素的最快方法 [英] Quickest way to find closest elements in an array in R
本文介绍了在R中找到数组中最接近元素的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在R中找到斋戒的方式,以识别最接近给定Xtimes值的Ytimes数组中元素的索引.
I would like find the fastes way in R to indentify indexes of elements in Ytimes array which are closest to given Xtimes values.
到目前为止,我一直在使用一个简单的for循环,但必须有一种更好的方法:
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])
推荐答案
R
是矢量化的,因此跳过for
循环.这样可以节省脚本和计算时间.只需将for
循环替换为apply
函数.由于我们要返回一维向量,因此我们使用sapply
.
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))})
证明apply
更快:
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)
请参见?apply for more
.
这篇关于在R中找到数组中最接近元素的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文