# Re: [R] converting NA/non-NA's to a binary variable

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Sat 07 May 2005 - 23:14:21 EST

mort[8] <- is.na(mort[4])

(If you really want 1/0, add '+ 0' to this expression.)

Testing (in)equality with NA always gives NA. This is discussed in all good books on S/R, e.g. in MASS (see the FAQ).

On Sat, 7 May 2005, Gillian Rutherford wrote:

> Dear R colleagues,
>
> I am trying to create a new column in a data frame, which converts values and
> NA's from another column into binary format. Essentially I need the NA's to
> become 1 and the rest to be 0. The code I wrote is returning the following
> error message:
>
> Error in if (mort[i, 4] != NA) mort[i, 8] <- 0 else if (mort[i, 4] == :
> missing value where TRUE/FALSE needed
>
> The code is as follows:
>
> for(i in 1:length(mort[,4]))
> {
> if(mort[i,4] != NA) mort[i,8] <- 0
> else if(mort[i,4] == NA) mort[i,8] <- 1
> }
>
> I'd appreciate any advice or recommendations as to a better way of achieving
> this.

```--
Brian D. Ripley,                  ripley@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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help