[R] sometimes removing NAs from code
William Dunlap
wdunlap at tibco.com
Wed Oct 26 17:54:35 CEST 2011
Instead of
d[-which(condition)]
use
d[!condition]
where 'condition' is a logical vector.
which(condition) returns integer(0) (an integer vector
of length 0) if there are no TRUEs in 'condition'.
-integer(0) is identical to integer(0) and d[integer(0)]
means to select zero elements from d.
!condition means to flip the senses of all the TRUEs and
FALSEs (and to leave NAs alone) so d[!condition] returns
the elements of d for which condition is not TRUE (along
with NA's for NA's in condition, but you won't have any
of them in your example).
By the way, your use of apply() slows things down and
might lead to errors. Try replacing
apply(adata[,1:2],1,function(x)any(is.na(x))))
by
is.na(adata$y) | is.na(adata$z)
or
rowSums(is.na(adata[,1:2])) > 0
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Schatzi
> Sent: Wednesday, October 26, 2011 8:25 AM
> To: r-help at r-project.org
> Subject: [R] sometimes removing NAs from code
>
> Sometimes I have NA values within specific columns of a dataframe (in this
> example, the first two columns can have NAs). If there are NA values, I
> would like them to be removed.
>
> I have been using the code:
>
> y<-c(NA,5,4,2,5,6,NA)
> z<-c(NA,3,4,NA,1,3,7)
> x<-1:7
> adata<-data.frame(y,z,x)
> adata<-adata[-which(apply(adata[,1:2],1,function(x)any(is.na(x)))),]
>
> This works well if there are NA values, but when a dataset doesn't have NA
> values, this code messes up the dataframe. I was trying to pick apart this
> code and could not understand why it didn't work when there were no NA
> values.
>
>
> If there are no NA values and I run just the part:
> apply(adata[,1:2],1,function(x)any(is.na(x)))
> it results in:
> 2 3 5 6
> FALSE FALSE FALSE FALSE
>
> I was thinking that I can put in an if statement, but I think there has to
> be a better way.
>
> Any ideas/help? Thank you.
>
> -----
> In theory, practice and theory are the same. In practice, they are not - Albert Einstein
> --
> View this message in context: http://r.789695.n4.nabble.com/sometimes-removing-NAs-from-code-
> tp3941009p3941009.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list