0

What is the correct way of writing if syntax on R?

With:

for ( i in 1:200 ) {
     if( (time[i]<731) | (time[i]==NA) ) { x[i] <- NA }
}

I keep getting:

missing value where TRUE/FALSE needed

The idea is to cut the beginning of the time series to calculate statistics. x and time are both numeric. Also this question is not an exact duplicate, the other post was dealing with a && statement and no foo==NA but foo==0. I thought that | or || would work like (TRUE | NA) = TRUE but it seems I was wrong.

user3083324
  • 585
  • 8
  • 23

3 Answers3

2

you can't write things like if (foo==NA) because comparing anything with NA returns NA. Instead, try

if( is.na(foo))
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
0

Try

is.na(x) <- (time < 731 | is.na(time))
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

Assuming you wanted:

> n = 10
> x <- rep(0, n)
> time <- rpois(n, 731)
> 
> for ( i in 1:n ) {
+   if( time[i] < 731 | is.na(time[i])) {  
+     x[i] <- NA
+   } 
+ }
> x
 [1]  0  0 NA NA NA  0 NA NA  0  0

You can do:

> ifelse(time < 731 | is.na(time[i]),  NA, x)
 [1]  0  0 NA NA NA  0 NA NA  0  0
Andrea
  • 593
  • 2
  • 8