Flay Auchter
Flay Auchter

Reputation: 145

Removing/ignoring NA values in an if loop

So I have this simple if loop

chick<-lapply(1:length(t),function(i){
if(t[[i]]<0.01){
chick=1
}else 0 
})

So basically when t<0.01 it print outs 1 if not it prints 0 but there are times when I have data that has NA values like the one below....how can I assign the NA values 0 as well coz I'll get an error similar to this if I dont:

Error in if (t[[i]] < 0.01) { : missing value where TRUE/FALSE needed

Here is a sample output from data called 't'

[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] 0.01

thanks again

Upvotes: 1

Views: 18804

Answers (4)

IRTFM
IRTFM

Reputation: 263301

Why not just this (invert the test and return 0 for the complementary test as well as for NA):

 chick <- ifelse(is.na(t)|t>=0.01, 0, 1)

This should work because FALSE|NA will return FALSE. See the ?Logic page. It's also more efficient that looping with lapply. I suppose if you need the results in list format you could eitehr do as.list to the results or use:

     if( is.na(t) || t>=0.01 ) { 0 }else{ 1 }

Upvotes: 0

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Or you could just use...

chick <- numeric( length(t) )
chick[ t < 0.01 ] <- 1 

... and avoid loops and checking for NA altogether.

Upvotes: 0

NPE
NPE

Reputation: 500157

The following with check whether t[[i]] is either NA or less than 0.01:

if (is.na(t[[i]]) || t[[i]] < 0.01) {
   ....

Upvotes: 0

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

use is.na

if(t[!is.na(t)][[i]]<0.01) ...

More importatnly though, since you are assigning to chick, do not try to also assign inside your lapply (or similar) statement. It will give you results different from what you are expecting. Instead try

chick <- lapply(1:length(t),function(i)  
  if(t[!is.na(t)][[i]]<0.01)  1  else 0 
)

Or better yet, use ifelse.

chick <- ifelse(t[!is.na(t)] < 0.01, 1, 0)

If you want chick to be the same length as t, then use the '|' operator in ifelse. as suggested by NPE (but use single | not || in ifelse)

Upvotes: 3

Related Questions