Challenge - 5 Problems
Factor Levels Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this factor levels code?
Consider the following R code that creates a factor and then changes its levels. What will be the output of
levels(f)?R Programming
f <- factor(c("low", "medium", "high", "medium", "low")) levels(f) <- c("low", "medium", "high", "very high") levels(f)
Attempts:
2 left
💡 Hint
The number of new levels must match the number of original levels exactly.
✗ Incorrect
The original factor has 3 levels: 'high', 'low', 'medium' (sorted alphabetically). Assigning 4 new levels causes an error because the number differs.
❓ Predict Output
intermediate2:00remaining
What is the output of this factor level drop code?
Given this R code, what will be the output of
levels(f) after dropping unused levels?R Programming
f <- factor(c("apple", "banana", "apple", "cherry"), levels = c("apple", "banana", "cherry", "date")) f <- droplevels(f[f != "date"]) levels(f)
Attempts:
2 left
💡 Hint
droplevels removes levels not present in the data.
✗ Incorrect
The original factor has 4 levels but 'date' is not present in the data. After subsetting and dropping levels, 'date' is removed.
🔧 Debug
advanced2:00remaining
Why does this factor level assignment cause an error?
Examine the code below. Why does assigning new levels cause an error?
R Programming
f <- factor(c("a", "b", "c")) levels(f) <- c("x", "y")
Attempts:
2 left
💡 Hint
The number of new levels must match the number of original levels.
✗ Incorrect
The original factor has 3 levels but the new levels vector has only 2 elements, causing an error.
❓ Predict Output
advanced2:00remaining
What is the output of this factor releveling code?
What will be the output of
levels(f) after running this code?R Programming
f <- factor(c("small", "medium", "large"), ordered = TRUE) f <- relevel(f, ref = "large") levels(f)
Attempts:
2 left
💡 Hint
relevel moves the specified level to the front.
✗ Incorrect
The relevel function moves the reference level to the first position in the levels vector.
🧠 Conceptual
expert2:00remaining
How many levels does this factor have after modification?
Given the code below, how many levels does the factor
f have after execution?R Programming
f <- factor(c("red", "green", "blue", "green"), levels = c("red", "green", "blue", "yellow")) f <- f[f != "yellow"] f <- droplevels(f) length(levels(f))
Attempts:
2 left
💡 Hint
droplevels removes unused levels after subsetting.
✗ Incorrect
The original factor has 4 levels but 'yellow' is not present in the data after subsetting, so droplevels removes it, leaving 3 levels.