Factor (R)
A factor is R's type for categorical data. It stores values as a set of discrete levels (categories) rather than plain text, which is essential for grouping, modeling, and ordered categories.
R
A factor encodes a categorical variable — like 'small/medium/large' or 'control/treatment' — as integer codes mapped to named levels. Internally the data is integers plus a levels attribute, which makes factors memory-efficient and tells statistical functions that the variable is categorical, not continuous.
Create one with factor(), and the distinct categories become its levels (alphabetical by default). For ordinal data, set ordered = TRUE and supply levels in order so comparisons like 'low' < 'high' work. This matters: in a model like lm(), a factor is automatically turned into the right set of indicator (dummy) variables.
A classic gotcha is that converting a factor straight to numeric with as.numeric() returns the integer codes, not the original numbers — use as.numeric(as.character(f)). Modern read.csv() keeps strings as characters by default (stringsAsFactors = FALSE), so you convert to factors deliberately.
Syntax
f <- factor(c("low", "high", "low"), levels = c("low", "high"))Examples
R
sizes <- factor(c("S", "L", "M", "S"))
print(levels(sizes))
print(table(sizes))Output:
[1] "L" "M" "S"
sizes
L M S
1 1 2