The “levels” Function in R
Package: Base R (no specific package required)
Purpose: Extracts or sets the levels of a factor.
General Class: Data Attribute
Required Argument(s):
For extraction, the factor whose levels are to be extracted.
For setting levels, the factor and the new levels to be assigned.
Notable Optional Arguments:
For setting levels, you can use levels(x) <- new_levels syntax to set new levels directly.
Example:
# Example data for using the levels attribute
colors <- c("Red", "Blue", "Green", "Red", "Green", "Blue")
color_factor <- factor(colors, levels = c("Red", "Blue", "Green"))
# Extract levels from the factor
extracted_levels <- levels(color_factor)
# Display the extracted levels
print(extracted_levels)
# Set new levels for the factor
new_levels <- c("Green", "Blue", "Red")
levels(color_factor) <- new_levels
# Display the factor with updated levels
print(color_factor)In this example, the levels function is used to extract the levels from a factor (color_factor). Later, the same function is used to set new levels for the factor. Note that the levels function is used as an attribute and applied to a factor object, rather than being a standalone function with arguments.