[R] sometimes removing NAs from code

jim holtman jholtman at gmail.com
Wed Oct 26 17:53:59 CEST 2011


?complete.cases

> 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
   y  z x
1 NA NA 1
2  5  3 2
3  4  4 3
4  2 NA 4
5  5  1 5
6  6  3 6
7 NA  7 7
> adata[complete.cases(adata),]
  y z x
2 5 3 2
3 4 4 3
5 5 1 5
6 6 3 6


On Wed, Oct 26, 2011 at 11:25 AM, Schatzi <adele_thompson at cargill.com> wrote:
> 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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list