【问题标题】:Finding local maxima and minima in R在R中找到局部最大值和最小值
【发布时间】:2016-03-16 07:15:34
【问题描述】:

我正在尝试创建一个函数来查找“最大值”和“最小值”。我有以下数据:

  y
  157
  144
   80
  106
  124
   46
  207
  188
  190
  208
  143
  170
  162
  178
  155
  163
  162
  149
  135
  160
  149
  147
  133
  146
  126
  120
  151
   74
  122
  145
  160
  155
  173
  126
  172
   93

我已经尝试过这个函数来找到“最大值”

localMaxima <- function(x) {
  # Use -Inf instead if x is numeric (non-integer)
  y <- diff(c(-.Machine$integer.max, 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
}

maks <- localMaxima(x)

寻找“最小值”的功能

localMinima <- function(x) {
      # Use -Inf instead if x is numeric (non-integer)
      y <- diff(c(.Machine$integer.max, 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
    }

    mins <- localMinima(x)

结果不是100%正确

maks = 1  5  7 10 12 14 16 20 24 27 31 33 35
mins = 3  6  8 11 13 15 19 23 26 28 32 34 36

结果应该

maks = 5  7 10 12 14 16 20 24 27 31 33 35
mins = 3  6  8 11 13 15 19 23 26 28 32 34

Finding local maxima and minima in R 接近,但不太合适。

我该如何解决这个问题?

非常感谢

【问题讨论】:

  • 如何定义局部最大值/最小值?两个相邻值较高/较低的位置?

标签: r minima


【解决方案1】:

这是我不久前写的一个函数(它比你需要的更通用)。它在顺序数据x 中找到峰值,其中我将峰值定义为局部最大值,其中m 点两侧的值低于它(因此更大的m 导致更严格的峰值查找标准):

 find_peaks <- function (x, m = 3){
     shape <- diff(sign(diff(x, na.pad = FALSE)))
     pks <- sapply(which(shape < 0), FUN = function(i){
        z <- i - m + 1
        z <- ifelse(z > 0, z, 1)
        w <- i + m + 1
        w <- ifelse(w < length(x), w, length(x))
        if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0))
    })
     pks <- unlist(pks)
     pks
}

所以对于你的情况m = 1:

 find_peaks(x, m = 1)
 #[1]  5  7 10 12 14 16 20 24 27 31 33 35

对于最小值:

 find_peaks(-x, m = 1)
 #[1]  3  6  8 11 13 15 19 23 26 28 32 34

【讨论】:

  • @stas_g..我正在使用您的解决方案。我只是想澄清一下,函数内部的'm = 3'。这是否意味着“默认”长度?所以如果我只输入 find_peaks(x) - 这将具有默认 m=3?
【解决方案2】:

您可以定义如下两个函数来生成您需要的向量:

library(data.table)
#shift lags or leads a vector by a certain amount defined as the second argument
#the default is to lag a vector.
#The rationale behind the below code is that each local minimum's adjucent
#values will be greater than itself. The opposite is true for a local 
#maximum. I think this is what you are trying to achieve and one way to do 
#it is the following code
maximums <- function(x) which(x - shift(x, 1) > 0  & x - shift(x, 1, type='lead') > 0)
minimums <- function(x) which(x - shift(x, 1) < 0  & x - shift(x, 1, type='lead') < 0)

输出:

> maximums(y)
 [1]  5  7 10 12 14 16 20 24 27 31 33 35
> minimums(y)
 [1]  3  6  8 11 13 15 19 23 26 28 32 34

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 2023-01-05
    • 2018-06-09
    • 2021-09-12
    相关资源
    最近更新 更多