查找峰的最近邻对的索引

Find the indices of the nearest neighbor pairs of a peak

我想知道是否有更直接的方法来找到向量 v 中最近邻居的位置,在峰值 p 之前和之后,它们接近或等于值 a

我有矢量 v、峰值 p 和值 a:

v <- c(4,7,1,4,12,10,9,6,2,8)
p <- 12
a <- 3

pv 内接近或等于 a 的最近邻居应该是

nn <- c(4,2)

nnv中的位置应该是

nn_pos <- c(4,9)
> tail(sort(v[v-a < 0]), 1)
[1] 2
> head(sort(v[v-a > 0]), 1)
[1] 4

我不确定你想如何使用峰值,但我认为你正在寻找的是这样的:

ppos <- which.min(abs(v - p))
dis <- abs(v - a)
output<- c(ppos - which.min(dis[(ppos-1):1]), ppos + which.min(dis[(ppos+1):length(v)]))
output
[1] 4 9
v[output]
[1] 4 2