[Rd] [R] Collapsing levels of a factor
Gregor Gorjanc
gregor.gorjanc at gmail.com
Mon Mar 20 06:50:55 CET 2006
>> x <- factor(1:3, labels = c("b" , "f", "minus"))
>> x
> [1] b f minus
> Levels: b f minus
>
> I want to change all "minus" to "b". I know that the simplest way to do this is
>
>> levels(x) <- c("b", "f", "b")
>
> and also that
>
>> x[x == "minus"] <- "b"
>> x <- factor(x)
>
> works. But why not
>
>> x <- ifelse(x == "minus", "b", x)
>> x <- factor(x)
> x
> [1] 1 2 b
> Levels: 1 2 b
>
I find particulary usefull the list approach. Here is the example from
levels help page. I like this approach, since you can modify list and
apply it to a factor via levels.
## we can add levels this way:
f <- factor(c("a","b"))
levels(f) <- c("c", "a", "b")
f
f <- factor(c("a","b"))
levels(f) <- list(C="C", A="a", B="b")
f
I was playing around this last week and wrote a simple function[1],
which can save you some work in getting such a list from a factor. Is R
core interested in it?
[1]http://www.bfro.uni-lj.si/MR/ggorjan/software/R/ggmisc/factorMap.R
--
Lep pozdrav / With regards,
Gregor Gorjanc
----------------------------------------------------------------------
University of Ljubljana PhD student
Biotechnical Faculty
Zootechnical Department URI: http://www.bfro.uni-lj.si/MR/ggorjan
Groblje 3 mail: gregor.gorjanc <at> bfro.uni-lj.si
SI-1230 Domzale tel: +386 (0)1 72 17 861
Slovenia, Europe fax: +386 (0)1 72 17 888
----------------------------------------------------------------------
"One must learn by doing the thing; for though you think you know it,
you have no certainty until you try." Sophocles ~ 450 B.C.
More information about the R-devel
mailing list