How do I create a function that defines a moving threshold along local maxima in R?

旧城冷巷雨未停 提交于 2021-02-11 14:01:01

问题


The goal is to quantify a certain growth. The definition is as follows: Every value in the sequence shall be compared to the preceding value and if the following value is greater than the preceding one, it shall be taken into regard (returned). If not, it shall be dropped. Consequently, the greater value is used as a new reference for the following ones. A threshold that moves with the ascending values. I've tried this:

growthdata<-c(21679, 21722, 21788, 21863, 21833, 21818, 21809, 21834, 21937, 22026, 22025, 22235, 22191, 22348, 22399, 22463, 22532, 22562, 22589, 22609, 22556, 22565)
growthfun<-function (a) {
  for (i in a) {
    if (i < (i+1)) {
      return(i)
    }
    else {
      next
      }
  }
}

It's a beginner's problem. I seem to be uncapable of defining the following value (i+1). The way I wrote it, R simply adds 1 to i's value. The result should look like this:

21679, 21722, 21788, 21863, 21937, 22026, 22235, 22348, 22399, 22463, 22532, 22562, 22589, 22609

Thanks in advance!


回答1:


There are some issues in your function growthfun:

  1. What you need might be print, not return. Otherwise, the function exits when the condition is met
  2. You may need the index of elements in a, which should be i in seq_along(a)

An example for you objective might be something like below:

  • If you want to print the progress, then use print
growthfun<-function (a) {
  for (i in seq_along(a)) {
    if (a[i] >= max(a[1:(i-1)])) {
      print(a[i])
    }
    else {
      next
    }
  }
}

which gives

> growthfun(growthdata)
[1] 21679
[1] 21722
[1] 21788
[1] 21863
[1] 21937
[1] 22026
[1] 22235
[1] 22348
[1] 22399
[1] 22463
[1] 22532
[1] 22562
[1] 22589
[1] 22609
  • If you want to save the output in an array
growthfun<-function (a) {
  r <- c()
  for (i in seq_along(a)) {
    if (a[i] >= max(a[1:(i-1)])) {
      r <- c(r,a[i])
    }
    else {
      next
    }
  }
  r
}

which gives

> growthfun(growthdata)
 [1] 21679 21722 21788 21863 21937 22026 22235 22348 22399 22463
[11] 22532 22562 22589 22609



回答2:


You can use cummax with only unique values.

unique(cummax(growthdata))
#[1] 21679 21722 21788 21863 21937 22026 22235 22348 22399 22463 22532 22562 22589 22609


来源:https://stackoverflow.com/questions/61288931/how-do-i-create-a-function-that-defines-a-moving-threshold-along-local-maxima-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!