[R] Recode factors
    Doran, Harold 
    HDoran at air.org
       
    Thu Mar 27 18:37:05 CET 2008
    
    
  
I know this comes up, but I didn't see my exact issue in the archives. I
have variables in a dataframe that need to be recoded. Here is what I'm
dealing with
I have a factor called aa
> class(aa)
[1] "factor"
> table(aa)
aa
        *    0    1    2    3    A    B    C    D    L    N    T 
   0    0 1908  725 2089    0    0   67    0    0    2    1    6 
I need to recode everything that is not a numeric value into a 0. So,
for example
> mm <- ifelse(aa == 'B', 0, aa)
> table(mm)
mm
   0    3    4    5   11   12   13 
  67 1908  725 2089    2    1    6 
The recoding works, but the values are no longer what they were
previously. For example, what was a '1' is now a '4' etc. Is there a way
to recode factors and also keep the values the same as they were before?
That is, a '1' would remain a '1' after the recode?
After the recoding, I need to convert to a numeric variable. I can do
this as
mm <- as.numeric(as.character(aa))
Harold
> sessionInfo()
R version 2.6.2 (2008-02-08) 
i386-pc-mingw32 
locale:
LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
States.1252;LC_MONETARY=English_United
States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
other attached packages:
[1] gdata_2.4.0
loaded via a namespace (and not attached):
[1] gtools_2.4.0
> 
    
    
More information about the R-help
mailing list