简体   繁体   中英

How to ignore NA in R?

I am doing some analysis and whenever NA is found, my loop stops which takes one by one. So I want to say if my value is not NA go ahead and further in the loop. if it is NA just ignore it and go for the next one. or even return NA . I tried this:

  x=c(5,4,6,4,2,1,5,NA)
  if (x != NA){
  y=x+2}


 Error in if (x != NA) { : missing value where TRUE/FALSE needed

x!=NA is neither TRUE nor FALSE, but NA. You can use the function is.na to check if something is NA or not:

> x=c(5,4,6,4,2,1,5,NA)
> x!=NA
[1] NA NA NA NA NA NA NA NA
> x==NA
[1] NA NA NA NA NA NA NA NA
> is.na(x)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
> y <- x[which(!is.na(x))]+2
> y
[1] 7 6 8 6 4 3 7
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM