Factors in R are used to store data that belongs to categories or groups. They help R understand that the data is not just numbers or text, but categories that can be ordered or unordered.
When you have survey answers like 'Yes', 'No', and 'Maybe'.
When you want to group data by colors like 'Red', 'Green', and 'Blue'.
When you have data about days of the week and want to keep their order.
When you want to save memory by storing repeated category names efficiently.
When you want to perform statistical analysis on groups or categories.
Syntax
R Programming
factor(x, levels = NULL, ordered = FALSE)
x is the vector of data you want to convert to categories.
levels lets you set the possible categories explicitly.
Examples
This creates a factor from a vector of color names.
C. levels() assignment should use factor() argument, not after
D. No error, code is correct
Solution
Step 1: Trace the code execution
factor(sizes, ordered=TRUE) creates an ordered factor with default alphabetical levels. Then levels(f) <- c('small', 'medium', 'large') reassigns levels in the desired order, which is valid.
Step 2: Verify no errors
Assigning levels after creation works for ordered factors and sets the order as listed. The code runs without error.
Final Answer:
No error, code is correct -> Option D
Quick Check:
levels(f) <- works on ordered factors [OK]
Hint: levels() <- assignment works after factor creation [OK]
Common Mistakes:
Thinking levels must only be set inside factor()
Believing ordered factors cannot have character levels
Assuming levels assignment fails after creation
5. You have a vector responses <- c('low', 'high', 'medium', 'low'). How do factors help when analyzing this data as categorical with a natural order?
hard
A. Factors allow defining levels with order: low < medium < high
B. Factors convert all responses to numeric values automatically
C. Factors remove duplicate values from the vector
D. Factors sort the vector alphabetically by default
Solution
Step 1: Understand natural order in categorical data
Responses like 'low', 'medium', 'high' have a natural order that factors can represent by setting ordered levels.
Step 2: How factors help analysis
By creating an ordered factor with levels c('low', 'medium', 'high'), R can compare and sort these categories meaningfully.
Final Answer:
Factors allow defining levels with order: low < medium < high -> Option A
Quick Check:
Ordered factors represent natural category order [OK]
Hint: Use ordered factors to keep category sequence [OK]
Common Mistakes:
Assuming factors convert to numbers automatically
Thinking factors remove duplicates
Confusing alphabetical sorting with natural order
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.