反转逻辑运算符会导致 R 函数失败?

Reversing logical operators causes R function to fail?

我有一个向量,它本质上是随时间记录的一系列数据点,例如-

data_vector <- c(5,21,25,26,67,24,15,11,15,19,27,28,22,14,11)

我想要一个函数,当数据超过用户定义的阈值时识别索引,无论是在数据减少还是增加。为了识别和输出随着数据减少而超过阈值(在本例中为 20.01)的值,此函数完成了工作 -

> x <- function(threshold){
+   crossing_points_down <- c()
+   for (i in 1:length(data_vector-1)) {
+     if ((data_vector[i] > threshold && data_vector[i+1] < threshold ) == TRUE) {
+       crossing_points_down <- append(crossing_points_down,i+1)
+     }
+   }
+   return(crossing_points_down)
+ }
> 
> x(20.01)
[1]  7 14

但是当逻辑运算符被反转来寻找向上的交叉点时,我得到这个错误-

> x <- function(threshold){
+   crossing_points_up <- c()
+   for (i in 1:length(data_vector-1)) {
+     if ((data_vector[i] < threshold && data_vector[i+1] > threshold ) == TRUE) {
+       crossing_points_up <- append(crossing_points_up,i+1)
+     }
+   }
+   return(crossing_points_up)
+ }
> 
> x(20.01)
Error in if ((data_vector[i] < threshold && data_vector[i + 1] > threshold) ==  : 
  missing value where TRUE/FALSE needed

知道为什么这两个函数的行为不同以及如何解决这个问题吗?

你的括号有误:

for (i in 1:(length(data_vector)-1)) {

但是,您不应该为此使用循环。这是一个矢量化的解决方案:

which(data_vector[-length(data_vector)] > 20.01 & 
        data_vector[-1] < 20.01) + 1
#[1]  7 14