[R] Collapsing levels of a factor

Göran Broström goran.brostrom at gmail.com
Fri Mar 17 14:12:46 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

?
--
Göran Broström




More information about the R-help mailing list