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

michael watson (IAH-C) michael.watson at bbsrc.ac.uk
Fri Jan 14 13:03:11 CET 2005


Thank you for the answers.  Checking for NAs using any() will help.
I just thought it was worth mentioning because the behaviour of data
frames (which throw an error) is different to the behaviour of matrices
(which don't), and that might not be expected.  

mat <- matrix(c(1,1,1,1),nrow=2,ncol=2)
mat[is.na(mat)] <- 0

mat <- matrix(c(1,1,1,NA),nrow=2,ncol=2)
mat[is.na(mat)] <- 0

-----Original Message-----
From: Prof Brian Ripley [mailto:ripley at stats.ox.ac.uk] 
Sent: 14 January 2005 11:57
To: michael watson (IAH-C)
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] Replacing NAs in a data frame using is.na() fails if
there are no NAs


On Fri, 14 Jan 2005, 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.

As always, look at the objects:

> is.na(df)
      c1    c2
1 FALSE FALSE
2 FALSE FALSE
3 FALSE FALSE

so there is nothing to replace by 0.

What you should have is

ind <- is.na(df)
df[ind] <- rep(0, sum(ind))

to give the right number of replacements.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list