[R] Problems with factor
ripley@stats.ox.ac.uk
ripley at stats.ox.ac.uk
Wed Jul 31 18:11:17 CEST 2002
On Wed, 31 Jul 2002, kjetil halvorsen wrote:
> Why does I get only the underlying representation, and not the level
> names, in the following code to recode a factor? Seems like a bug to me.
You have coercion going on there. Here is a simpler example:
> x <- factor(letters)
> ifelse(x=="a", "a", x)
[1] "a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15"
[16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26"
S does the same.
>From the help page
`ifelse' returns a value with the same shape as `test' which is
filled with elements selected from either `yes' or `no' depending
on whether the element of `test' is `TRUE' or `FALSE'.
Note that there is no mention of carrying attributes across from yes or no.
I think you want something like
Malaria$TratUl <- Malaria$Trat
Malaria$TratUl[Malaria$DiaC>0] <-
ifelse(Malaria$Trat=="QT", "SP", "QT")[Malaria$DiaC>0]
since that only works with character vectors on the RHS.
>
> > attach(Malaria)
> > Malaria$TratUl <- factor(ifelse(Malaria$DiaC>0,
> + ifelse(Malaria$Trat=="QT", "SP", "QT"),
> + Malaria$Trat))
> > Malaria$TratUl
> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 QT 2 2 2 2 2 QT
> QT 2
> [25] 2 2 QT 2 2 2
> Levels: 1 2 QT
> > Malaria$Trat
> [1] QT QT QT QT QT QT QT QT QT QT QT QT QT QT QT SP SP SP SP SP SP SP
> SP SP
> [25] SP SP SP SP SP SP
> Levels: QT SP
--
Brian D. Ripley, ripley at 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 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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