Challenge - 5 Problems
Factor Creation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of factor levels with default ordering
What is the output of the following R code?
f <- factor(c("apple", "banana", "apple", "cherry"))
levels(f)R Programming
f <- factor(c("apple", "banana", "apple", "cherry")) levels(f)
Attempts:
2 left
💡 Hint
Think about how R orders factor levels by default.
✗ Incorrect
By default, R orders factor levels alphabetically. So the levels are "apple", "banana", "cherry".
❓ Predict Output
intermediate2:00remaining
Number of levels in a factor
What is the output of this R code?
f <- factor(c("red", "blue", "red", "green", "blue"))
length(levels(f))R Programming
f <- factor(c("red", "blue", "red", "green", "blue")) length(levels(f))
Attempts:
2 left
💡 Hint
Count unique values in the vector.
✗ Incorrect
The factor has three unique values: "red", "blue", and "green", so the number of levels is 3.
❓ Predict Output
advanced2:00remaining
Effect of specifying levels in factor creation
What is the output of this R code?
f <- factor(c("small", "medium", "large", "medium"), levels = c("large", "medium", "small"))
levels(f)R Programming
f <- factor(c("small", "medium", "large", "medium"), levels = c("large", "medium", "small")) levels(f)
Attempts:
2 left
💡 Hint
Levels are set explicitly in the factor function.
✗ Incorrect
When levels are specified, R uses that order exactly for the factor levels.
❓ Predict Output
advanced2:00remaining
Output of factor with unused levels
What is the output of this R code?
f <- factor(c("cat", "dog"), levels = c("cat", "dog", "mouse"))
length(levels(f))R Programming
f <- factor(c("cat", "dog"), levels = c("cat", "dog", "mouse")) length(levels(f))
Attempts:
2 left
💡 Hint
Levels include all specified, even if not used in data.
✗ Incorrect
The factor has three levels because "mouse" is included even though it does not appear in the data.
🧠 Conceptual
expert2:30remaining
Behavior of factor when converting numeric vector
Consider this R code:
What is the output of
v <- c(10, 20, 10, 30) f <- factor(v) levels(f)
What is the output of
levels(f)?R Programming
v <- c(10, 20, 10, 30) f <- factor(v) levels(f)
Attempts:
2 left
💡 Hint
Factor levels are always character strings representing unique values.
✗ Incorrect
When a numeric vector is converted to a factor, levels are character strings of unique values sorted.