[R] converting NA/non-NA's to a binary variable
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Sat May 7 15:47:19 CEST 2005
On 07-May-05 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.
>
> Thanks
> Gillian
I think the following should do what you want, provided the column
mort[,8] exists:
mort[,8] <- 0
mort[is.na(mort[,4]),8] <- 1
Incidentally, tests like "== NA" or "!= NA" can produce unexpected
results! Use is.na() instead:
tmp<-NA
## [1] NA
tmp==NA
## [1] NA
tmp!=NA
## [1] NA
if(tmp==NA) 1 else 2
## Error in if (tmp == NA) 1 else 2 :
## missing value where TRUE/FALSE needed
if(TRUE) 1 else 2
## [1] 1
is.na(tmp)
## [1] TRUE
if(is.na(tmp)) 1 else 2
## [1] 1
if(!is.na(tmp)) 1 else 2
## [1] 2
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-May-05 Time: 14:46:19
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list