R:找到低于阈值的连续值

时间:2016-05-10 14:25:56

标签: r threshold

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

有人可以帮帮我!! :)

1 个答案:

答案 0 :(得分:2)

以下内容适用于您所要求的内容:

# 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,则表示数据中没有此类观察值。如果length为1或greate,则可以使用

# 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。