Factors in R
Factors in R
Introduction
A factor is a data structure in R used to represent categorical data. Categorical data consists of a limited number of distinct values called levels. Factors are widely used in statistical analysis, machine learning, and data analysis.
Examples of categorical variables are:
- Gender (Male, Female)
- Blood Group (A, B, AB, O)
- Grade (A, B, C, D)
- Department (CSE, ECE, ME)
- Marital Status (Single, Married)
Unlike character vectors, factors store the categories internally as integers and maintain a set of corresponding labels called levels.
Why Use Factors?
Factors provide:
- Efficient storage of repeated categorical values.
- Information about the categories (levels).
- Easy statistical analysis.
- Support for ordered categories.
- Compatibility with modeling functions in R.
Creating Factors
Factors are created using the factor() function.
Syntax
factor(x)
where x is a vector containing categorical values.
Example 1: Gender
gender <- c("Male", "Female", "Male", "Male", "Female")
f <- factor(gender)
print(f)
Output
[1] Male Female Male Male Female
Levels: Female Male
Internal Representation
as.numeric(f)
Output
[1] 2 1 2 2 1
Internally:
| Category | Code |
|---|---|
| Female | 1 |
| Male | 2 |
Determining Factor Properties
class()
class(f)
Output
[1] "factor"
levels()
Returns the categories.
levels(f)
Output
[1] "Female" "Male"
length()
Returns the number of elements.
length(f)
Output
[1] 5
nlevels()
Returns the number of categories.
nlevels(f)
Output
[1] 2
Creating Factors with Specified Levels
blood <- factor(
c("B","A","O","AB","A"),
levels=c("A","B","AB","O")
)
print(blood)
Output
[1] B A O AB A
Levels: A B AB O
Frequency Table
table(blood)
Output
A B AB O
2 1 1 1
Accessing Factor Elements
blood[3]
Output
[1] O
Levels: A B AB O
Modifying Factor Elements
gender[1] <- "Female"
print(gender)
Output
[1] "Female" "Female" "Male" "Male" "Female"
Adding Levels
Suppose
gender <- factor(c("Male","Female","Male"))
Current levels:
Female Male
Add a new level:
levels(gender) <- c(levels(gender), "Other")
Now
gender[1] <- "Other"
print(gender)
Output
[1] Other Female Male
Levels: Female Male Other
Renaming Levels
levels(gender) <- c("F","M","O")
print(gender)
Output
[1] O F M
Levels: F M O
Ordered Factors
Some categories have a natural order.
Examples:
- Small < Medium < Large
- Poor < Average < Good < Excellent
Such factors are called ordered factors.
Example
grade <- factor(
c("Good","Excellent","Average","Good"),
levels=c("Poor","Average","Good","Excellent"),
ordered=TRUE
)
print(grade)
Output
[1] Good Excellent Average Good
Levels: Poor < Average < Good < Excellent
Comparing Ordered Factors
grade[1] > grade[3]
Output
[1] TRUE
because
Good > Average
Converting Character Vector to Factor
dept <- c("CSE","ECE","ME","CSE")
f <- factor(dept)
print(f)
Output
[1] CSE ECE ME CSE
Levels: CSE ECE ME
Converting Factor to Character
as.character(f)
Output
[1] "CSE" "ECE" "ME" "CSE"
Converting Factor to Numeric
Suppose
x <- factor(c("10","20","30"))
Incorrect
as.numeric(x)
Output
[1] 1 2 3
These are level numbers, not actual values.
Correct
as.numeric(as.character(x))
Output
[1] 10 20 30
Using Factors in Data Frames
student <- data.frame(
Name=c("John","Mary","Alex"),
Gender=factor(c("Male","Female","Male"))
)
print(student)
Output
Name Gender
1 John Male
2 Mary Female
3 Alex Male
Counting Categories
gender <- factor(c("Male","Female","Male","Male"))
table(gender)
Output
Female Male
1 3
Summary of Factor Values
summary(gender)
Output
Female Male
1 3
Useful Functions
| Function | Purpose |
|---|---|
factor() | Create factor |
levels() | Display levels |
nlevels() | Number of levels |
table() | Frequency of levels |
summary() | Summary of factor |
as.character() | Convert factor to character |
as.numeric() | Convert to numeric codes |
class() | Determine class |
Difference Between Character Vectors and Factors
| Character Vector | Factor |
|---|---|
| Stores text directly | Stores categories as integers |
| No levels | Has levels |
| Less efficient | More memory efficient |
| No ordering | Can be ordered |
| Used for text | Used for categorical data |
Applications of Factors
Gender Classification
Male, Female
Student Grades
A, B, C, D
Blood Groups
A, B, AB, O
Shirt Sizes
Small, Medium, Large
Customer Categories
Silver, Gold, Platinum
Disease Severity
Mild, Moderate, Severe
Example: Student Grade Analysis
grades <- factor(
c("A","B","A","C","B","A")
)
print(table(grades))
Output
A B C
3 2 1
Conclusion
Factors are specialized data structures used to represent categorical data. They store categories efficiently using integer codes and maintain a set of levels corresponding to the categories. Factors play a crucial role in statistical analysis, machine learning, and data modeling, making them one of the most important data structures in R.
Comments
Post a Comment