Skip to content
Prev 69842 / 398525 Next

NA erase your data trick

On Tue, 17 May 2005, Uwe Ligges wrote:

            
That will work if tcn5 contains NAs, but only because NA indices on the 
lhs are now ignored for matrices (if tcn5 is a matrix, which seems 
unstated) -- this used not to be the case.  I would prefer

     tcn5[tcn %in% -9] <- NA

Using %in% rather than == in computed indices is a good habit to acquire: 
it also makes things like

     tcn5[tcn %in% c(-9, -99)] <- NA

work as expected.

If tcn is a data frame, you have to do this column-by-column, as in

tcn5[] <- lapply(tcn5, function(x) x[x %in% -9] <- NA)

or by a logical index matrix, which is harder to construct.