[R] creating a factor from other factors and ifelse

Gabor Grothendieck ggrothendieck at gmail.com
Sun Nov 27 06:39:01 CET 2005


We don't need the inner if, ifelse does not work with factors as
I think you expect and in any case we really want to create a new
factor with a new set of levels consisting of those in the new variable

sec.char <- ifelse(is.na(sec99), as.character(sec00), as.character(sec99))
factor(sec.char)

or maybe the union of the original levels of sec99 and sec00 regardless
of whether they are in the resulting factor variable or not:

factor(sec.char, levels = union(levels(sec99), levels(sec00)))

(In this case the two factor calls above give the same result but in
general they could differ in the levels.)


On 11/26/05, dimitrijoe at ipea.gov.br <dimitrijoe at ipea.gov.br> wrote:
>
>
> Hi,
>
> Given
>
> > sec98 <- factor(rep(1:2,3), labels=c("A", "B"))
> > sec99 <- factor(rep(2:1,3), labels=c("A", "B"))
> >    sec99[c(2,5)] <- NA
> > sec00 <- factor( c( rep(1,3), rep(2,3) ), labels=c("A", "B"))
> >    sec00[c(2,4)] <- NA
> > sec1 <- ifelse(!is.na(sec99), sec99,
>        ifelse(!is.na(sec00), sec00, NA ))
>
> We get
>
> > sec1; class(sec1)
> [1]  2 NA  2  1  2  1
> [1] "integer"
>
> I wonder why sec1 as above defined  in not a factor, since it has been
> created from (logical operations and) factors. Of course, one could do
>
> > sec1 <- factor(sec1, labels=levels(sec99))
>
> but this would be a problem if I had (as I actually do) sec99 and sec00
> instead defined as
>
> > sec99 <- factor(c(1,2,3,2,3,3), labels=c("A", "B", "C"))
> >   sec99[c(2,5)] <- NA
> > sec00 <- factor(c(4,1,1,2,4,2), labels=c("A", "B", "D"))
> >    sec00[c(2,4)] <- NA
>
>    # because
> > sec1 <- ifelse(!is.na(sec99), sec99,
> >        ifelse(!is.na(sec00), sec00, NA ))
>
>    # gives us
> > sec1; class(sec1)
> [1]  1 NA  3  2  3  3
> [1] "integer"
>
> now it's hard to tell where each "3" in sec1 means "C" or "D". What I
> actually wanted was
>
> > sec1; class(sec1)
> [1]  A <NA>  C  B  D  C
> [1] "factor"
>
> Any suggestions on how to do it in a simple way will be welcome.
> Thanks,
> Dimitri
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list