# Re: [R] factor : how does it work ?

From: Florence Combes <fcombes_at_gmail.com>
Date: Fri 07 Oct 2005 - 00:20:08 EST

> > > 2d I can't manage to deal with factors, so when I have some, I
> transform
> > > them in vectors (with levels()), but I think I miss the power and
> utility
> > of
> > > the factor type ?
> >
> > levels() is not the conversion you want.

in fact I use
'as.numeric(levels(f))[f]'

(from the ?factor description)

That lists all the levels, but
> > it doesn't tell you how they correspond to individual observations. For
> > example,
> >
> > > df <- data.frame(x=1:3, y=c('a','b','a'))
> > > df
> > x y
> > 1 1 a
> > 2 2 b
> > 3 3 a
> > > levels(df\$y)
> > [1] "a" "b"
> >
> > If you need to convert back to character values, use as.character():
> >
> > > as.character(df\$y)
> > [1] "a" "b" "a"

got it.

> > 1. You can't compare the levels of a factor unless you declared it to
> > be ordered:
> >
> > > df\$y[1] > df\$y[2]
> > [1] NA
> > Warning message:
> > > not meaningful for factors in: Ops.factor(df\$y[1], df\$y[2])
> >
> > but
> >
> > > df\$y <- ordered(df\$y)
> > > df\$y[1] > df\$y[2]
> > [1] FALSE
> >
> > However, you need to watch out here: the comparison is done by the order
> > of the factors

, not an alphabetic comparison of their names:
> >
> > > levels(df\$y) <- c("before", "after")
> > > df
> > x y
> > 1 1 before
> > 2 2 after
> > 3 3 before
> > > df\$y[1] > df\$y[2]
> > [1] FALSE
best regards,

[[alternative HTML version deleted]]

R-help@stat.math.ethz.ch mailing list