[R] creating a factor from other factors and ifelse

dimitrijoe@ipea.gov.br dimitrijoe at ipea.gov.br
Sun Nov 27 02:57:28 CET 2005



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




More information about the R-help mailing list