0
votes

I received the error

Error in if (x[i] == 0 && x[i - 1] > 0) { : 
  missing value where TRUE/FALSE needed

when running this function on a numeric vector

number_rn <- function(x) {
  a <- 0
  for (i in 1:length(x)) {
    if (x[i] == 0 && x[i-1] > 0) {
      a <- a +1
    }
  }
  print(a)
}

However, the following function works fine:

number_rr <- function(x) {
  a <- 0
  for (i in 1:length(x)) {
    if (x[i] > 0 && x[i-1] > 0) {
      a <- a +1
    }
  }
  print(a)
}

I note from previous answers to similar questions that this can occur if the if conditional does not have either a TRUE or FALSE result, but I do not believe this to be the case in my example. What could be causing this error?

2
What vector did you run the function on? - duckmayr
it's likely that i is bigger than x's length. anyway one of your term is NA, check i, x[i], x[i-1] ... - Moody_Mudskipper

2 Answers

1
votes

There are several issues with the for loop (even if x does not contain any NA values):

  1. In the first iteration (i == 1), x[i-1] refers to x[0] which is undefined as indexing in R starts at 1.
  2. The code is using a for loop where vectorized functions can be used.

Unfortunately, starting the loop at i == 2, i.e., for (i in 2:length(x)), is not error-proof in case of a one element vector where length(x) == 1.

My suggestion is to use the vectorized version

number_rn_vec <- function(x) {
  n <- length(x)
  sum(x[2:n] == 0 & x[1:(n - 1)] > 0, na.rm = TRUE)
}

This will return a without error for many use cases:

sapply(
  list(
    c(),
    c(1),
    c(1, 0),
    c(1, 0, 3),
    c(0, 1, 0, 3),
    c(NA, 1, 0, 3),
    c(1, NA, 0, 3),
    c(1, 0, NA, 3),
    c(1, 0, 3, NA)
  ),
  number_rn_vec
)
[1] 0 0 1 1 1 1 0 1 1
0
votes

This is most likely occurring because you vector x has NULL or NA values. See what happens when I try to run a if condition with NULL values -

x <- NULL
if (x == 0 && x > 5) print("yes")

Make sure to remove any NAs or NULLs using is.na() or is.null() and you should be fine