作为一个愚蠢的玩具例子,假设
x=4.5
w=c(1,2,4,6,7)我想知道是否有一个简单的R函数可以在x中找到与w最接近的索引。因此,如果foo是该函数,foo(w,x)将返回3。函数match是正确的想法,但似乎只适用于精确匹配。
解决方案这里 (例如which.min(abs(w - x))、which(abs(w-x)==min(abs(w-x)))等)都是O(n)而不是log(n) (我假设w已经排序了)。
发布于 2013-11-21 22:48:44
您可以使用data.table进行二进制搜索:
dt = data.table(w, val = w) # you'll see why val is needed in a sec
setattr(dt, "sorted", "w") # let data.table know that w is sorted注意,如果列w尚未排序,则必须使用setkey(dt, w)而不是setattr(.)。
# binary search and "roll" to the nearest neighbour
dt[J(x), roll = "nearest"]
# w val
#1: 4.5 4在最后一个表达式中,val列将包含您要查找的内容。
# or to get the index as Josh points out
# (and then you don't need the val column):
dt[J(x), .I, roll = "nearest", by = .EACHI]
# w .I
#1: 4.5 3
# or to get the index alone
dt[J(x), roll = "nearest", which = TRUE]
#[1] 3发布于 2015-04-10 03:38:16
R>findInterval(4.5, c(1,2,4,5,6))
[1] 3将与价格是正确的匹配(最近而不超过)。
发布于 2018-10-02 18:52:23
请参见match.closest()包中的MALDIquant:
> library(MALDIquant)
> match.closest(x, w)
[1] 3https://stackoverflow.com/questions/20133344
复制相似问题