我正在寻找一种可重现的方法来查找给定序列中的最新局部峰值(以及最近的谷值)。在大多数情况下,这里的答案-Finding local maxima and minima起作用,除了以下情况外,我从此链接中使用了汤米的答案,因为它似乎是最可靠的。
x <- c(0.4,0.5,0.5,0.4,0.4,0.3,0.3)
localMaxima <- function(x) {
# Use -Inf instead if x is numeric (non-integer)
y <- diff(c(-Inf, x)) > 0L
rle(y)$lengths
y <- cumsum(rle(y)$lengths)
y <- y[seq.int(1L, length(y), 2L)]
if (x[[1]] == x[[2]]) {
y <- y[-1]
}
y
}
>localMaxima(x)
[1] 2
在这种情况下,应该返回[1] 3
而不是2,因为这是最近的点(最近的数据点是向量的结尾)。
用rev(x)反转向量将不起作用,因为没有可靠的方法来确定是否必须反转向量。