# ============================================================
# Factors: Categorical Data
# R Foundations — Rverse Analytics
# https://rverseanalytics.com/learn/factors
# ============================================================

# Categorical data is stored as a factor
class(iris$Species)
levels(iris$Species)
table(iris$Species)
# Build a factor with a meaningful order
sz <- factor(c("S", "L", "M", "S", "L"), levels = c("S", "M", "L"))
sz
as.integer(sz)   # the codes follow the level order
# Factors drive grouping in plots and models
boxplot(Sepal.Length ~ Species, data = iris,
        col = c("#17a2b8", "#2f6fed", "#5aa0ff"))
# Choose which level is the reference (baseline)
sp <- relevel(iris$Species, ref = "versicolor")
levels(sp)
