由于if else函数导致R函数出错

时间:2018-01-25 07:40:01

标签: r

我想创建一个简单的函数来执行数值积分。它循环执行一个简单的if else检查的值。对于我的生活,我不明白为什么我得到下面显示的错误。任何帮助将不胜感激。

代码是

Vel <- function(Acc, dt) {
    L <- length(Acc) # obtain the length of the Accellerogram
    V <- rep(0, L) # create a vector of 0s of length L
    for (i in 1:L-1) {
        Test <- Acc[i] * Acc[i+1]  
        if (Test >= 0) { # i.e. are the two values either both +ve or both -ve
            V[i+1] <- V[i] + dt * (Acc[i] + Acc[i+1]) / 2
        }
        else {         # i.e. if the one value is +ve and one -ve
            dtt <- Acc[i] / ((Acc[i] - Acc[i+1]) / dt)    
            V[i+1] <- V[i] + 0.5 * Acc[i] * dtt + 0.5 * Acc[i+1] * (dt-dtt)
        } 
    }
}

Acc <- c(0,1,0.5,1,-3,-2,0)
dt <- 0.005
V <- Vel(Acc,dt)

    Error in if (Test >= 0) { : missing value where TRUE/FALSE needed

1 个答案:

答案 0 :(得分:2)

将L-1放在括号中

Vel<- function(Acc,dt){
      L<- length(Acc) # obtain the length of the Accellerogram
      V <- rep(0,L) # create a vector of 0s of length L
      for (i in 1:(L-1)){
        Test <- Acc[i] * Acc[i+1]  
        if (Test >= 0) { # i.e. are the two values either both +ve or both -ve
          V[i+1] <- V[i] + dt * (Acc[i] + Acc[i+1]) / 2
        } else {         # i.e. if the one value is +ve and one -ve
          dtt <- Acc[i] / ((Acc[i] - Acc[i+1]) / dt)    
          V[i+1] <- V[i] + 0.5 * Acc[i] * dtt + 0.5 * Acc[i+1] * (dt-dtt)
        } 
      }
    }