3

我正在寻找一个函数,它可以从我提供的起点开始在向量上进行简单的爬山。更正式地说:给定一个类似的向量y <- c(1,2,3,1,1),我想要一个函数hill(y, x0),使得hill(y, 1) == 3(从左边爬到顶部)和hill(y, 5) == 5(它左右移动,但发现它处于高原,只返回起始值)。我很难相信这不存在,但到目前为止还没有找到。有人有线索吗?

4

3 回答 3

2

这是一个递归解决方案,来自https://gist.github.com/3000200。为简洁起见省略了测试。

climb <- function(y, x0) {
  x <- index(y)
  n <- length(y)

  if (n == 0) { return(NA) }

  if (x0 < min(x) | x0 > max(x)) {
    warning(sprintf("x0 of %f lies outside data range [%f, %f]", x0, min(x), max(x)))
  }

  # TODO: beautify this.
  w <- which.min(abs(as.numeric(x - x0)))
  i <- x[w]
  ii <- index(x)[w] # 1-based index
  l <- x[ii-1]
  r <- x[ii+1]
  yl <- if (ii == 1) { -Inf } else { as.numeric(y[l]) }
  yr <- if (ii == n) { -Inf } else { as.numeric(y[r]) }
  yi <- as.numeric(y[i])

  # At a maximum?
  if (yl <= yi && yr <= yi) {
    return(i)
  }

  # Nope; go in the direction of greatest increase, breaking ties to the right.
  if (yl > yr) {
    return(climb(y, l))
  } else {
    return(climb(y, r))
  }
}
于 2012-06-27T16:32:08.040 回答
1

I don't think there is a function that will do that, the task is too simple and specialized. The more general case is that of finding local maxima in a vector or time series:

Given x, then [could be written as one-liner]

lmax <- function(x) {
    x <- c(x[1], x, x[length(x)])
    d <- diff(sign(diff(x)))
    which(d < 0)
}

will return the indices of all (local) maxima in x. Starting with some index i it is now easy to find the highest maximum in its vicinity. Example:

x <- c(10,10, 9, 4,10,10,10, 1, 2, 5, 4, 4)
lmax(x)                                     # 2  5  7 10

If you start with i = 4 you will have to look -- applying findInterval, for instance -- which one is higher, x[2] or x[5]. If you don't want to wade through flat valleys (or plateaus), e.g. i=6, some if statements will march in. Therefore a pedestrian's approach seems more appropriate:

hill <- function(x, i) {
    stopifnot(is.numeric(x), 1 <= i, i <= length(x))
    i1 <- i2 <- i
    while (i1 < length(x))
        if (x[i1 + 1] > x[i1]) i1 <- i1 + 1 else break
    while (i2 > 1)
        if (x[i2 - 1] > x[i2]) i2 <- i2 - 1 else break
    # return
    if (x[i1] >= x[i2]) i1 else i2
}

Of course, I would like to see a more vectorized solution.

于 2012-06-27T12:36:59.547 回答
0

我怀疑您正在寻找cumsum或正在寻找cummax您的数学问题:

?cummax  # on same help page as cumsum

> y <- c(1,2,3,1,1)
> cummax(y)
[1] 1 2 3 3 3
> cumsum(y)
[1] 1 3 6 7 8

但后来我在 RSeek.org 上搜索了“爬山”,发现你想要别的东西。包中有这样的功能:例如,hill.climbing.search在“FSelector”中。

于 2012-06-26T20:37:04.057 回答