[R] Replacing NAs in a data frame using is.na() fails if there are no NAs

Sean Davis sdavis2 at mail.nih.gov
Fri Jan 14 13:05:01 CET 2005


Mick,

The actual error is telling:

 > df <- data.frame(c1=c(1,1,1),c2=c(2,2,2))
 > df[is.na(df)] <- 0
Error in "[<-.data.frame"(`*tmp*`, is.na(df), value = 0) :
	rhs is the wrong length for indexing by a logical matrix

If you look at is.na(df), you will see that it is all FALSE, of course. 
  The right-hand-side (rhs) can't be assigned to a vector of length=0 
(the length of df[is.na(df)] if there are no NAs), hence the error.  An 
easy work-around is to check if there are NAs first.

tmp <- is.na(df); #get total number of NAs
if (sum(tmp)) {   #only execute if there is at least one NA
	df[tmp] <- 0
}

Sean


On Jan 14, 2005, at 6:20 AM, michael watson ((IAH-C)) wrote:

> Hi
>
> This is a difference between the way matrices and data frames work I
> guess.  I want to replace the NA values in a data frame by 0, and the
> code works as long as the data frame in question actually includes an 
> NA
> value.  If it doesn't, there is an error:
>
> df <- data.frame(c1=c(1,1,1),c2=c(2,2,NA))
> df[is.na(df)] <- 0
> df
>
> df <- data.frame(c1=c(1,1,1),c2=c(2,2,2))
> df[is.na(df)] <- 0
> Df
>
> Any help would be appreciated.  I could just convert the data frame to 
> a
> matrix, execute the code, then convert it back to a data frame, but 
> that
> appears long winded.
>
> Thanks
> Mick
>
> ______________________________________________
> 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