R factor() function - Creating factors
R factor() function is used to create factors (categorical variables).
Factors are a core concept in R for handling categorical data, automatically generating dummy variables in statistical modeling.
The syntax format of the factor() function is as follows:
factor(x, levels, labels = levels, ordered = FALSE)
Parameter description:
xThe vector to be converted to a factor.
levelsThe levels of the factor (optional, default in alphabetical order).
labelsLabels for the levels.
orderedWhether it is an ordered factor.
Example
# Create a basic factor
gender <- factor(c("Male", "Female", "Male", "Female", "Male"))
print("Gender factor:")
print(gender)
print("Levels:")
print(levels(gender))
# Create an ordered factor (education level)
edu <- factor(c("Bachelor", "Master", "Bachelor", "PhD", "Bachelor"),
levels = c("Bachelor", "Master", "PhD"),
ordered = TRUE)
print("Education factor:")
print(edu)
print(paste("Bachelor < Master?", edu[1] < edu[2]))
# Application of factors in statistics
scores <- c(88, 92, 76, 85, 90)
avg_by_gender <- tapply(scores, gender, mean)
print("Average score by gender:")
print(avg_by_gender)
gender <- factor(c("Male", "Female", "Male", "Female", "Male"))
print("Gender factor:")
print(gender)
print("Levels:")
print(levels(gender))
# Create an ordered factor (education level)
edu <- factor(c("Bachelor", "Master", "Bachelor", "PhD", "Bachelor"),
levels = c("Bachelor", "Master", "PhD"),
ordered = TRUE)
print("Education factor:")
print(edu)
print(paste("Bachelor < Master?", edu[1] < edu[2]))
# Application of factors in statistics
scores <- c(88, 92, 76, 85, 90)
avg_by_gender <- tapply(scores, gender, mean)
print("Average score by gender:")
print(avg_by_gender)
Executing the above code produces the following output:
[1] "性别因子:" [1] 男 女 男 女 男 Levels: 男 女 [1] "水平:" [1] "男" "女" [1] "学历因子:" [1] 本科 硕士 本科 博士 本科 Levels: 本科 < 硕士 < 博士 [1] "本科 < 硕士? TRUE" [1] "按性别平均分:" 男 女 88.0 88.5Other Extensions
R Language Examples