0
0
R Programmingprogramming~20 mins

Factor levels in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Factor Levels Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AError: number of levels differs from previous
B[1] "low" "medium" "high"
C[1] "low" "medium" "high" "very high" "extreme"
D[1] "low" "medium" "high" "very high"
Attempts:
2 left
💡 Hint
The number of new levels must match the number of original levels exactly.
Predict Output
intermediate
2: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)
A[1] "apple" "banana" "cherry" "date"
BError: object 'f' not found
C[1] "apple" "banana"
D[1] "apple" "banana" "cherry"
Attempts:
2 left
💡 Hint
droplevels removes levels not present in the data.
🔧 Debug
advanced
2: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")
ABecause the new levels vector contains invalid characters
BBecause factor levels cannot be changed once created
CBecause the new levels vector has fewer elements than the original levels
DBecause the factor vector contains NA values
Attempts:
2 left
💡 Hint
The number of new levels must match the number of original levels.
Predict Output
advanced
2: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)
A[1] "small" "medium" "large"
B[1] "large" "small" "medium"
C[1] "medium" "small" "large"
DError: object 'relevel' not found
Attempts:
2 left
💡 Hint
relevel moves the specified level to the front.
🧠 Conceptual
expert
2: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))
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
droplevels removes unused levels after subsetting.