Complete the code to create a factor from a character vector.
colors <- c("red", "blue", "green", "red") factor_colors <- factor([1]) print(factor_colors)
as.factor instead of the vector.c("red", "blue").levels which is not a vector.The factor() function converts a vector into a factor, which represents categorical data. Here, we pass the vector colors to create the factor.
Complete the code to get the levels of a factor.
colors <- factor(c("red", "blue", "green", "red")) levels_list <- [1](colors) print(levels_list)
unique() which works on vectors but not specifically for factor levels.as.character() which converts factor to string but does not list levels.class() which returns the type, not levels.The levels() function returns the categories (levels) of a factor, showing the distinct groups it represents.
Fix the error in the code to correctly create a factor with specified levels.
colors <- c("red", "blue", "green", "red") factor_colors <- factor(colors, levels = [1]) print(factor_colors)
The levels argument must include all categories present in the vector to avoid missing or unexpected values. Here, all colors are included.
Fill both blanks to create a factor and check if it is a factor.
data <- c("small", "medium", "large", "medium") f <- [1](data) is_fact <- [2](f) print(is_fact)
as.factor is also valid to create a factor but here factor is expected.is.character returns FALSE because the object is a factor, not a character vector.factor() creates a factor from a vector. is.factor() checks if an object is a factor, returning TRUE or FALSE.
Fill all three blanks to create a factor with ordered levels and check if it is ordered.
sizes <- c("small", "medium", "large", "medium") ordered_sizes <- factor(sizes, levels = [1], ordered = [2]) is_ordered <- [3](ordered_sizes) print(is_ordered)
is.factor() instead of is.ordered() will not check ordering.To create an ordered factor, specify the levels in order and set ordered = TRUE. Then is.ordered() checks if the factor is ordered.