Factors: Categorical Data in R
Groups, categories, treatment arms β R stores them as factors, and using them well makes your models and plots behave. Everything below is a live R console β edit the code and press Run Code.
Watch: factors in R
What a factor is, how to set its level order, and why it drives grouping in plots and models.
Download the R script Β· βΆ Practice in the playground β or edit and run each snippet below.
A column that holds categories
The Species column of iris is a factor. levels() lists its categories; table() counts them:
Set a meaningful order
Build your own factor and fix the level order β this controls how categories are coded and displayed:
Factors drive grouping
Pass a factor on the right of a ~ formula and R splits the outcome by group automatically:
Choose the reference level
relevel() picks the baseline your models compare everything against:
Your turn
Next: Missing values (NA) β β coping with the gaps in real data.