đ Introduction
A factor is a special data structure in R used to represent categorical data. Categorical data consists of a fixed set of possible values, known as levels. Factors are commonly used in statistical analysis, data visualization, and machine learning because they efficiently store categories and preserve their relationships.
Information
đ¯ Why Use Factors?
- Represent categorical data efficiently.
- Reduce memory usage compared to storing repeated text values.
- Support statistical modeling and analysis.
- Maintain consistent category values.
- Work seamlessly with data frames and visualization libraries.
đĻ Creating Factors
The factor() function is used to create a factor from a vector.
Creating a Factor
gender <- factor(c("Male", "Female", "Female", "Male"))
print(gender)Output
Console Output
[1] Male Female Female Male
Levels: Female Maleđˇ Understanding Levels
The unique categories stored in a factor are called levels. By default, R arranges levels in alphabetical order.
Viewing Levels
gender <- factor(c("Male", "Female", "Female", "Male"))
levels(gender)Output
Console Output
[1] "Female" "Male"đ Creating Factors with Custom Levels
You can explicitly specify the order of levels using the levels argument.
Custom Levels
grade <- factor(
c("B", "A", "C", "A"),
levels = c("A", "B", "C")
)
print(grade)
levels(grade)đĸ Ordered and Unordered Factors
An unordered factor represents categories with no natural order.
Unordered Factor
color <- factor(
c("Red", "Blue", "Green")
)
print(color)An ordered factor represents categories with a meaningful sequence.
Ordered Factor
size <- factor(
c("Medium", "Large", "Small"),
levels = c("Small", "Medium", "Large"),
ordered = TRUE
)
print(size)đ Checking Factor Information
| Function | Description | Example |
|---|---|---|
| levels() | Returns factor levels. | levels(x) |
| nlevels() | Returns the number of levels. | nlevels(x) |
| class() | Returns the data type. | class(x) |
| str() | Displays the internal structure. | str(x) |
Factor Functions
gender <- factor(c("Male", "Female", "Male"))
print(levels(gender))
print(nlevels(gender))
print(class(gender))
str(gender)âī¸ Modifying Factor Levels
Existing factor levels can be renamed by assigning new values to the levels() function.
Renaming Levels
gender <- factor(c("M", "F", "F", "M"))
levels(gender) <- c("Female", "Male")
print(gender)â Adding Levels
New levels can be added using the levels() function before assigning them to elements.
Adding a New Level
department <- factor(c("HR", "IT"))
levels(department) <- c(levels(department), "Finance")
department[3] <- "Finance"
print(department)â Removing Unused Levels
After deleting or filtering data, unused levels can be removed using the droplevels() function.
Removing Unused Levels
colors <- factor(c("Red", "Blue", "Green"))
colors <- colors[1:2]
colors <- droplevels(colors)
print(colors)
levels(colors)đ Frequency of Categories
The table() function counts the number of occurrences of each factor level.
Counting Categories
gender <- factor(
c("Male", "Female", "Male", "Female", "Male")
)
table(gender)Output
Console Output
gender
Female Male
2 3đ Converting Between Data Types
Factors can be converted to character or numeric values when required.
Type Conversion
grade <- factor(c("A", "B", "C"))
as.character(grade)
numbers <- factor(c("10", "20", "30"))
as.numeric(as.character(numbers))Warning
đ§ Factor Workflow
đ Real-World Example
The following example stores employee departments as a factor and calculates the number of employees in each department.
Employee Departments
department <- factor(
c("HR", "IT", "Finance", "IT", "HR", "IT")
)
print(department)
levels(department)
table(department)đ Character Vector vs Factor
| Feature | Character Vector | Factor |
|---|---|---|
| Purpose | Stores text values. | Stores categorical data. |
| Levels | No | Yes |
| Memory Efficiency | Lower for repeated values. | Higher for repeated categories. |
| Statistical Analysis | Limited | Widely supported. |
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Using as.numeric() directly on a factor | Returns internal level codes instead of displayed values. | Convert to character first. |
| Assigning a value not present in the levels | R generates an invalid level warning. | Add the new level before assignment. |
| Ignoring unused levels | Unused categories remain in the factor. | Use droplevels() to remove them. |
| Using a factor for free-form text | Factors are intended for predefined categories. | Use character vectors for unrestricted text. |
đĄ Best Practices
- Use factors only for categorical data.
- Define factor levels explicitly whenever the category order matters.
- Use ordered factors for ranked categories.
- Convert factors carefully when performing numerical calculations.
- Remove unused levels after filtering data.
Best Practice
đ Summary
Factors are specialized data structures designed for storing and analyzing categorical data in R. You learned how to create factors, define and modify levels, distinguish between ordered and unordered factors, convert factors to other data types, and use built-in functions such as levels(), nlevels(), and table(). Mastering factors is essential for data analysis, statistical modeling, and working effectively with categorical variables in R.