[R] Merging factor levels.

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Tue Nov 13 13:52:04 CET 2001


Göran Broström <gb at stat.umu.se> writes:

> Thanks to John and Brian, who helped me out on this one. But, one question 
> about 'ifelse' and factors remains to be answered:
> 
> > table(okk)
> okk
>      Other   STORKAGE SKELLEFTEA    FALMARK       BOLE 
>      14098        560        346        526        332 
> 
> > for (i in 1:length(okk)) if(okk[i] == "BOLE") okk[i] <- "Other"
> > table(okk)
> okk
>      Other   STORKAGE SKELLEFTEA    FALMARK       BOLE 
>      14430        560        346        526          0 
> > is.factor(okk)
> [1] TRUE
> 
> works. I think of 'ifelse' as a replacement for the loop, so why doesn't
> it work here? 
...
> > > > > okk <- ifelse(okk == "NEAR_TOWN", "Other", okk)
> > > > > table(okk)
> > > > okk
> > > >     1     2     3     4     5 Other
> > > > 14064   560   346   526   332    34
> > > > > is.factor(okk)
> > > > [1] FALSE

This is a quirk of ifelse (and an S-PLUS compatible quirk): factor
arguments are converted to integer. Even in this case:

 x <- factor(LETTERS)
 ifelse(rep(TRUE,26),x,x)

If there is a logic to this, then it would probably be that ifelse()
can't know whether to take attributes from the "if" or the "else"
parts, so it deletes attributes from both.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list