如何创建定义沿R中局部最大值的移动阈值的函数? [英] How do I create a function that defines a moving threshold along local maxima in R?

查看:62
本文介绍了如何创建定义沿R中局部最大值的移动阈值的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是量化一定的增长.定义如下:序列中的每个值都应与前一个值进行比较,如果后一个值大于前一个值,则应将其考虑在内(返回).如果没有,应将其丢弃.因此,较大的值将用作以下值的新参考.随值上升而变化的阈值.我已经尝试过了:

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
      }
  }
}

这是初学者的问题.我似乎无法定义以下值(i + 1).按照我写的方式,R只是将i的值加1.结果应如下所示:

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

提前谢谢!

推荐答案

函数 growthfun 中存在一些问题:

  1. 您需要的是 print ,而不是 return .否则,当满足条件时该函数将退出
  2. 您可能需要 a 中元素的索引,该索引应为seq_along(a)
  3. 中的 i
  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:

  • 如果要打印进度,请使用 print
growthfun<-function (a) {
  for (i in seq_along(a)) {
    if (a[i] >= max(a[1:(i-1)])) {
      print(a[i])
    }
    else {
      next
    }
  }
}

给出

> 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

  • 如果要将输出保存在数组中
  • 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
    }
    

    给出

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

    这篇关于如何创建定义沿R中局部最大值的移动阈值的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆