How to deal with NA when using lappy in R

183 views Asked by At

I have a data frame err consisting of 796 rows and 54432 columns

I have to check the columns that have values not exceeding 20 and -20.

This is my approach:

do.call(cbind, (lapply(err, function(x) if((all(x<20)  & all(x>-20))) return(x) )))

I Have NA values in all of the columns and after i got

Error in if ((all(x < 20) & all(x > -20))) return(x) :
  missing value where TRUE/FALSE needed

I update the command using !is.na as:

 do.call(cbind, (lapply(err, function(x) if(!is.na(all(x<20)  & all(x>-20))) return(x) )))

But in this case all the columns are reported and the filter does not work.

Any help?

2

There are 2 answers

3
mts On BEST ANSWER

Since I don't have an example df check if this works for you:

do.call("cbind", lapply(err, function(x) if(min(x, na.rm=T) > -20  & max(x, na.rm=T) < 20) return(x) ))
0
Veerendra Gadekar On

Using apply

err[apply(err, 2, function(x) min(x,na.rm=T) > -20 & max(x,na.rm=T) < 20)]