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

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Jan 14 12:49:47 CET 2005


michael watson (IAH-C) wrote:

> 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.

  Slightly less long-winded (but probably a worse solution than some 
R-guru is about to give you) would be to stick a row of NAs at the end 
of the dataframe, do your replacement, then remove the last row. This 
slightly reminds me of the old joke about algorithms for hunting 
elephants in Africa, which involve placing a known elephant at the Cape 
Of Good Hope so that the algorithm is guaranteed to terminate, like all 
good algorithms should...

  But probably better to test for NAs in the dataframe beforehand:

    if(any(is.na(f)))f[is.na(f)]=0


Baz




More information about the R-help mailing list