0

I have a code like that in R

for (index in c(1:nrow(my_data) - 2)){
  if (!is.na(my_data[index, 1]) && !is.na(my_data[index + 1, 1]) && !is.na(my_data[index + 2, 1])) {
    print("yes")
  }
}

but I have the error

Error in if (!is.na(my_data[index, 1]) && !is.na(my_data[index + 1, 1]) &&  : 
  missing value where TRUE/FALSE needed

What's wrong with this code?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 3
    Welcome to StackOverflow please read [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) . – fabla Jul 25 '20 at 09:13

2 Answers2

2

The : operator takes precedence over the - operator, so the code c(1:nrow(my_data) - 2) doesn't do what you think it does. Suppose my_data is a data frame with 10 rows. Then your code is the same as c(1:10 - 2)

This is not the same as 1:8. It is the same as taking 2 away from each member of the set 1:10. Your indexing therefore starts at -1, which of course is not defined, and causes your error.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
-1

Put nrow(my_data)-2 inside brackets.

This should work

for (index in c(1:(nrow(my_data) - 2))){
  if (!is.na(my_data[index, 1]) && !is.na(my_data[index + 1, 1]) && !is.na(my_data[index + 2, 1])) {
    print("yes")
  }
}
Shubham Pujan
  • 210
  • 2
  • 7