【问题标题】:R: Find consecutive values beneath thresholdR:查找阈值以下的连续值
【发布时间】:2021-04-22 23:35:33
【问题描述】:

我需要在风速测量的 data.frame 中找到小于某个阈值的连续值。我正在寻找低于阈值的 2 个连续观察值。我想返回符合这些条件的系列的第一次观察的位置。

【问题讨论】:

标签: r threshold


【解决方案1】:

以下内容应该可以满足您的要求:

# create random vector, for example
set.seed(1234)
temp <- rnorm(50)

# get position of all observations that fulfill criterion, here obs is > 0.2
thresholdObs <- which(temp > .2)

这里,which 返回满足某个标准的所有观测值的位置。此时,谨慎的做法是测试是否有任何观察结果满足您的标准。这可以通过intersect 函数或子集与%in% 运算符一起实现:

length(intersect(thresholdObs, thresholdObs + 1))

length(thresholdObs[thresholdObs %in% (thresholdObs + 1L)])

如果返回长度 0,则您的数据中不存在此类观察结果。如果长度为 1 或更大,则可以使用

# get the answer
min(thresholdObs[thresholdObs %in% (thresholdObs + 1L)] - 1)

min(intersect(thresholdObs, thresholdObs + 1))-1

正如@Frank 下面所指出的,如果min 被输入一个长度为0 的向量,它会返回Inf,这意味着R 中的无穷大。我增加这些位置thresholdObs + 1 并取这两组的交集。返回的唯一位置是前一个位置通过阈值测试的位置。然后我从这些位置中减去 1 并取最小值以获得所需的结果。因为which 会返回一个有序的结果,所以下面的也可以工作:

intersect(thresholdObs, thresholdObs + 1)[1] - 1

[1] 提取交集中的第一个元素。

还要注意

intersect(thresholdObs, thresholdObs + 1) - 1

thresholdObs[thresholdObs %in% (thresholdObs + 1L)]

将返回至少有两个连续元素通过阈值的所有位置。但是,对于连续超过阈值且大于 2 的值,将返回多个位置。

【讨论】:

  • 您的示例数据给出了 Inf,因为交集是空的,这就是 min(numeric(0)) 给出的。更安全/更简单的可能是w = which(temp &gt; .5); w[ w %in% (w + 1L) ]
  • @Frank 这似乎是一个更安全的选择。
猜你喜欢
  • 2020-06-12
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
相关资源
最近更新 更多