Factors
A factor stores categories from a fixed set, like T-shirt sizes small, medium, and large. R keeps track of the allowed choices and their order.
In this page:
Syntax
factor_name <- factor(c("level1", "level2"), levels = c("level1", "level2"))
levels(factor_name)
Factors
A factor represents categorical data with a fixed, known set of possible values (called levels), such as "low", "medium", "high".
Factors are created with factor() and store the data more efficiently than plain strings while also enabling proper statistical treatment of categories. levels() lists the distinct categories a factor can take.
Note:
Use factor(x, levels = c(...), ordered = TRUE) when the categories have a meaningful order, like small < medium < large.
Example: Factors
sizes <- factor(c("small", "large", "medium", "small"),
levels = c("small", "medium", "large"))
print(sizes)
print(levels(sizes))
print(table(sizes))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Converting a factor of numbers with
as.numeric(f), which returns the level codes, not the original values. - Assigning a value that is not one of the levels, such as
sizes[1] <- "huge", which givesNAwith a warning. - Forgetting to set
levelsin order, so "large" sorts before "medium" and "small" alphabetically.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: