0
0
R Programmingprogramming~5 mins

Factor levels in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a factor in R?
A factor in R is a data structure used to represent categorical data. It stores the data as integer codes with corresponding character labels called levels.
Click to reveal answer
beginner
How do you create a factor with specific levels in R?
Use the factor() function with the levels argument. For example: factor(c("low", "high", "medium"), levels = c("low", "medium", "high")) creates a factor with levels ordered as low, medium, high.
Click to reveal answer
intermediate
What happens if you assign a value not in the levels to a factor?
R will convert that value to NA (missing value) because it is not recognized as one of the factor's predefined levels.
Click to reveal answer
beginner
How can you see the levels of a factor variable in R?
Use the levels() function. For example, levels(my_factor) returns a character vector of the factor's levels.
Click to reveal answer
intermediate
Why is the order of factor levels important?
The order of factor levels affects how R orders and compares the categories. For example, in plots or summary statistics, the order controls the display and sorting.
Click to reveal answer
What does the levels() function return when used on a factor?
AThe data type of the factor
BThe numeric codes of the factor
CThe length of the factor
DA character vector of the factor's categories
What happens if you create a factor with levels = c("low", "medium") but include "high" in the data?
A"high" becomes NA because it's not in the levels
B"high" is automatically added to levels
CAn error is thrown
D"high" is ignored silently
How do you create an ordered factor in R?
AUse factor() with ordered = TRUE
BUse levels() function
CUse as.character()
DUse numeric()
Why might you want to set the order of factor levels explicitly?
ATo convert factors to numeric
BTo speed up calculations
CTo control the order of categories in plots and summaries
DTo remove missing values
Which function converts a character vector to a factor in R?
Afactor()
BBoth A and B
Clevels()
Das.factor()
Explain what factor levels are and why they matter in R.
Think about how R stores categories and how order affects results.
You got /4 concepts.
    Describe how to create a factor with custom levels and what happens if data contains values outside those levels.
    Consider the factor() function and the levels parameter.
    You got /3 concepts.