# R: Factors

### From MathWiki

Q: The default reference level using treatment contrasts for a factor in a model formula is the level that is first in alphabetical order. How can I change it to another level?

A: Suppose that your factor is f:

> f <- factor(c('b','b','c','a')) > f [1] c a b c a Levels: a b c

The default contrasts have 'a' as the reference level:

> contrasts(f) b c a 0 0 b 1 0 c 0 1

You can change the order of levels with:

> ff <- factor(f , levels = c('c','b','a')) > ff [1] c a b c a Levels: c b a

which makes 'c' the reference level:

> contrasts(ff) b a c 0 0 b 1 0 a 0 1

**Use with lm:**

Suppose ff is the order of the qualitative variable f to fit in a linear regression of Y with other quantitative variables X1, X2. Simply replace f with ff in the lm argument, i.e.,

> fit <- lm( Y ~ X1 + X2 + ff )