[R] removing NA from a data frame

Haifeng Xie xieh at wmin.ac.uk
Sat Mar 18 00:25:34 CET 2006


If I understand it correctly, something like this should do what you want

x[!apply(x, 1, function(y) any(is.na(y)), ]

where x is the dataframe in question.

Hope that helps.

Kevin


----- Original Message ----- 
From: "Ben Bolker" <bolker at ufl.edu>
To: <r-help at stat.math.ethz.ch>
Sent: Friday, March 17, 2006 10:33 PM
Subject: Re: [R] removing NA from a data frame


> Sam Steingold <sds <at> podval.org> writes:
>
>>
>> Hi,
>> It appears that deal does not support missing values (NA), so I need to
>> remove them (NAs) from my data frame.
>> how do I do this?
>> (I am very new to R, so a detailed step-by-step
>> explanation with code samples would be nice).
>
>  If you wanted to remove rows with NAs from data frame X
> na.omit(X) would do it.
>
>  In this case I think
>
> X[!sapply(X,function(z)any(is.na(z)))]
>
> should work, although I haven't tested it.
> function(z)any(is.na(z)) looks for any NA values
> sapply applies the function to each element
> in the list (= column in the data frame) and
> returns a vector
> ! negates the logical vector
> [] picks the appropriate elements (=columns) out
> of the list (=dataframe)
>
>  I haven't tested it.
>  Conceivably
>
> X[!sapply(is.na(X),any)]
>
> or
>
> X[sapply(!is.na(X),all)]
>
> would work too, although I'm not sure.
>
>  Ben
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list