Factors in
R Programming
Master how R handles categorical data using factors: create them, inspect their levels, and convert between factor and character types.
R Programming
What is a Factor?
A factor is R's special data type for representing categorical variables: data that takes a fixed, known set of values called levels. Think of survey responses like "Agree", "Neutral", "Disagree" or shirt sizes like "S", "M", "L", "XL".
Why Do Factors Matter?
Statistical Models
Functions like lm() and glm() automatically create dummy variables from factors for regression analysis.
Controlled Levels
Factors restrict data to predefined categories, catching typos and invalid entries during data cleaning.
Custom Ordering
Ordered factors let you define meaningful sequences like "Low" < "Medium" < "High" for plots and summaries.
Anatomy of a Factor
Creating Factors with factor()
# Basic factor creation
sizes <- factor(c("M", "S", "L", "M", "S"))
print(sizes)
# [1] M S L M S
# Levels: L M S
# With custom levels (controls order)
sizes2 <- factor(
c("M", "S", "L", "M"),
levels = c("S", "M", "L")
)
levels(sizes2)
# [1] "S" "M" "L"
Key Factor Functions
levels(x)
Returns the character vector of all possible categories for factor x.
nlevels(x)
Returns the number of levels (equivalent to length(levels(x))).
is.factor(x)
Returns TRUE or FALSE: tests whether an object is a factor.
as.numeric(x)
Returns the internal integer codes, not the displayed values. Use with caution!
Factor vs Character
| Factor | Character | |
|---|---|---|
| Storage | Integer codes + level labels | Raw character strings |
| Fixed categories | ✓ Yes | ✕ No |
| Order support | ✓ Yes (ordered) | Alphabetical only |
| Used in lm()/glm() | ✓ Auto dummy vars | Coerced to factor first |
| Add new value | Must add level first | Just assign it |
Converting: Factor → Character
status <- factor(c("Pass", "Fail", "Pass"))
# Convert factor → character
status_chr <- as.character(status)
print(status_chr)
# [1] "Pass" "Fail" "Pass"
class(status_chr)
# [1] "character"
# Level info is gone:
levels(status_chr)
# NULL
Converting: Character → Factor
colors <- c("red", "blue", "red", "green")
# Convert character → factor
colors_fct <- as.factor(colors)
print(colors_fct)
# [1] red blue red green
# Levels: blue green red
# Or with factor() for custom levels
colors_fct2 <- factor(colors,
levels = c("red", "green", "blue")
)
levels(colors_fct2)
# [1] "red" "green" "blue"
Step-by-Step: Working with Factors
1
Identify categorical columns. Look for columns with repeated text values: survey responses, categories, groups.
2
Create the factor. Use factor(x, levels = ...) to define categories and their order explicitly.
3
Verify with str() and levels(). Confirm the type is "Factor" and levels are in the expected order.
4
Convert when needed. Use as.character() to get labels, or as.numeric(as.character(x)) to safely extract numbers from factor labels.
5
Use ordered = TRUE when there is a natural ordering: "low" < "medium" < "high".
Example 1: Survey Responses
# Raw survey data
responses <- c("Agree", "Disagree", "Neutral",
"Agree", "Agree", "Neutral")
# Create ordered factor
resp_fct <- factor(responses,
levels = c("Disagree", "Neutral", "Agree"),
ordered = TRUE
)
print(resp_fct)
# [1] Agree Disagree Neutral Agree Agree Neutral
# Levels: Disagree < Neutral < Agree
# Now we can compare:
resp_fct[1] > resp_fct[3]
# [1] TRUE (Agree > Neutral)
Example 2: The Numeric Trap
# Factor with numeric-looking labels
scores <- factor(c("10", "20", "30", "20"))
# WRONG: as.numeric returns internal codes!
as.numeric(scores)
# [1] 1 2 3 2 ← NOT 10, 20, 30!
# RIGHT: convert via character first
as.numeric(as.character(scores))
# [1] 10 20 30 20 ← Correct!
Example 3: Modifying Factor Levels
grade <- factor(c("A", "B", "C", "A"))
# Rename levels
levels(grade) <- c("Excellent", "Good", "Average")
print(grade)
# [1] Excellent Good Average Excellent
# Levels: Excellent Good Average
# Add a new level without data
levels(grade) <- c(levels(grade), "Poor")
levels(grade)
# [1] "Excellent" "Good" "Average" "Poor"
# Drop unused levels
grade2 <- droplevels(grade)
Conversion Flowchart
Common Mistakes
✕ as.numeric() on Factor
Returns internal integer codes instead of the label values. Always convert through as.character() first.
✕ Assigning Unlisted Values
Setting a value not in levels produces NA with a warning. Add the level first with levels().
✕ Ignoring Level Order
Default alphabetical order puts "High" before "Low". Specify levels = c("Low", "Medium", "High") explicitly.
Summary Reference Table
| Operation | R Code | Result |
|---|---|---|
| Create factor | factor(x) | Factor with alphabetical levels |
| Custom levels | factor(x, levels = ...) | Factor with specified order |
| Get levels | levels(x) | Character vector of levels |
| Factor → Character | as.character(x) | Plain character vector |
| Character → Factor | as.factor(x) | Factor with alpha levels |
| Factor → Numeric (safe) | as.numeric(as.character(x)) | Actual numeric values |
| Ordered factor | factor(x, ordered = TRUE) | Factor with < ordering |
Question 1 of 5
What does R store internally when you create a factor?
Factors store integers under the hood, with each integer corresponding to a position in the levels vector. This is more memory-efficient than storing repeated strings.
Question 2 of 5
Given: x <- factor(c("30", "10", "20"))
What does as.numeric(x) return?
Levels default to alphabetical: "10"=1, "20"=2, "30"=3. So as.numeric() returns the internal codes: c(3, 1, 2). To get the actual numbers, use as.numeric(as.character(x)).
Question 3 of 5
Which function converts a factor back to a character vector?
as.character() extracts the label text for each element, producing a plain character vector. levels() returns only the unique level names, not the full vector of values.
Question 4 of 5
You run: f <- factor(c("A","B","A"), levels = c("B","A"))
What does levels(f) return?
When you specify the levels argument, R uses that exact order. Since we wrote levels = c("B", "A"), the levels are stored as c("B", "A"), overriding the default alphabetical sort.
Question 5 of 5
What happens when you assign a value not in the levels to an existing factor element?
R does not automatically expand factor levels. Assigning an unlisted value sets that element to NA with a warning message: "invalid factor level, NA generated". You must add the level first using levels(x) <- c(levels(x), "new_value").