Factors

Factors are a variable type used for categorial data.

Whenever a data frame is created with text strings, R treats it as a factor.

Want to learn more? I recommend working through: R for Data Science, R Cookbook, and R Graphics Cookbook.

# Create three variables of 50 observations length.
turnout <- runif(50)
state <- state.name
outcome <- c("win", "loss")
# Create a dataframe of those two variables
usa <- data.frame(state, turnout, outcome)
# Is "outcome" a factor? Yes.
class(usa$outcome)
[1] "factor"
# View the levels (i.e. category names) of the factor
levels(usa$outcome)
[1] "loss" "win"
# views the number of these levels (i.e. category IDs) of the factor
nlevels(usa$outcome)
[1] 2
# change levels of a factor
levels(usa$outcome) <- c("victory", "defeat")