relevel
Reorder Levels of Factor

Description

Reorders the levels of an existing factor. The reference level is moved to the first position and the others retain their original order.

Usage

relevel(x, ref, ...)

Arguments

x a factor.
ref a character string matching a string in levels(x), or an integer index into levels(x) to specify which level to use as the reference level.
... reserved for future use.

Details

This is a generic function. Some S3 methods are implemented for class factor, ordered, and default. An error is returned for ordered and default.
Value
returns a factor with the same length as x, where the first level is the desired reference level.
See Also
factor, levels, contr.treatment.
Examples
dose <- factor(c(.1, .4, 1.2, .1, .4, 1.2, .4))
response <- c(10, 15, 29, 9, 13, 33, 14)
dose
dose2_ <- relevel(dose, "0.4") # move second level, "0.4", to front
dose2_
relevel(dose, 2) # alternate way to do same thing
tapply(response, list(dose=dose2_), mean) # mean response by dose
# The following assumes getOption("contrasts")[1] == "contr.treatment"
coefficients(lm(response ~ dose)) # effects relative to dose=0.1
coefficients(lm(response ~ dose2_)) # effects relative to dose=0.4
Package stats version 6.1.1-7
Package Index