# [R] Collapsing levels of a factor

Gabor Grothendieck ggrothendieck at gmail.com
Fri Mar 17 14:21:34 CET 2006

```The problem is that ifelse strips attributes.  For example, consider
this which has nothing to do with factors but illustrates the point
with ifelse:

> x <- ts(1:12)
> y <- ifelse(TRUE, x, x)
> str(x)
Time-Series [1:12] from 1 to 12: 1 2 3 4 5 6 7 8 9 10 ...
> str(y)
int 1

On 3/17/06, Göran Broström <goran.brostrom at gmail.com> wrote:
> > 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help