[R] numeric variables converted to character when recoding missing values

Juan Pablo Lewinger lewinger at usc.edu
Sat Jun 24 00:00:16 CEST 2006

Dear R helpers,

I have a data frame where missing values for numeric variables are coded as
999. I want to recode those as NAs. The following only partially succeeds
because numeric variables are converted to character in the process:

df <- data.frame(a=c(999,1,999,2), b=LETTERS[1:4])
is.na(df[2,1]) <- TRUE

    a b
1 999 A
2  NA B
3 999 C
4   2 D

[1] TRUE

is.na(df[!is.na(df) & df==999]) <- TRUE
     a b
1 <NA> A
2    1 B
3 <NA> C
4    2 D

[1] TRUE

My question is how to do the recoding while avoiding this undesirable side
effect. I'm using R 2.2.1 (yes, I know 2.3.1 is available but don't want to
switch mid project). I'd appreciate any help.

Further details:

platform i386-pc-mingw32
arch     i386           
os       mingw32        
system   i386, mingw32  
major    2              
minor    2.1            
year     2005           
month    12             
day      20             
svn rev  36812          
language R              

Juan Pablo Lewinger
Department of Preventive Medicine 
Keck School of Medicine 
University of Southern California

More information about the R-help mailing list