</>
Skip to content
R lessons (12/41)

R — Factors

Creating factors

# Basic factor
colors <- factor(c("red", "blue", "green", "red", "blue"))
print(colors)
print(levels(colors))

# Ordered factor
sizes <- factor(c("small", "medium", "large", "medium"),
                levels = c("small", "medium", "large"),
                ordered = TRUE)
print(sizes)

Factor operations

# Summary
colors <- factor(c("red", "blue", "green", "red", "blue", "red"))
summary(colors)

# Table
table(colors)

# Levels
levels(colors)
nlevels(colors)

Modifying factors

# Add level
levels(colors) <- c(levels(colors), "yellow")

# Rename levels
levels(colors) <- c("Red", "Blue", "Green")

# Reorder
colors <- factor(colors, levels = c("Green", "Red", "Blue"))

Factors in data frames

df <- data.frame(
  color = factor(c("red", "blue", "green")),
  size = factor(c("S", "M", "L"), levels = c("S", "M", "L"), ordered = TRUE)
)

str(df)
summary(df)

Using forcats

library(forcats)

# fct_reorder
df <- data.frame(
  category = factor(c("C", "A", "B", "A", "C")),
  value = c(10, 20, 15, 25, 12)
)
df$category <- fct_reorder(df$category, df$value)

# fct_lump
colors <- factor(c("red", "blue", "green", "red", "red", "blue", "other"))
fct_lump(colors, n = 2)

Mini Practice

Write R code that:

  1. Creates an ordered factor
  2. Uses summary on a factor
  3. Modifies factor levels
  4. Uses forcats for factor manipulation

Up Next

In the next lesson, you'll learn about Strings — working with text in R.

Related Topics

Frequently Asked Questions about Factors

What is Factors in R?

Factors is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Factors?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Factors.

Why is Factors important in R?

Factors is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.