R factor() Function - Creating Factors
The 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 of the factor() function is as follows:
factor(x, levels, labels = levels, ordered = FALSE)
Parameter Description:
-
x The vector to be converted into a factor.
-
levels The levels of the factor (optional, in alphabetical order by default).
-
labels Display labels for the levels.
-
ordered Whether it is an ordered factor.
Example
Create a basic factor
gender
<-
factor
(
c
(
"male"
,
"female"
,
"male"
,
"female"
,
"male"
)
)
(
"Gender factor:"
)
(
gender
)
(
"Levels:"
)
(
levels
(
gender
)
)
Create an ordered factor (education level)
edu
<-
factor
(
c
(
"Bachelor"
,
"Master"
,
"Bachelor"
,
"Doctor"
,
"Bachelor"
)
,
levels
=
c
(
"Bachelor"
,
"Master"
,
"Doctor"
)
,
ordered
=
TRUE
)
(
"Education factor:"
)
(
edu
)
(
paste
(
"Bachelor < Master?"
, edu
[
1
]
<
edu
[
2
]
)
)
scores
<-
c
(
88
,
92
,
76
,
85
,
90
)
avg_by_gender
<-
tapply
(scores, gender,
mean
)
(
"Average score by gender:"
)
(
avg_by_gender
)
The output of the code above is:
[1] "性别因子:"
[1] 男 女 男 女 男
Levels: 男 女
[1] "水平:"
[1] "男" "女"
[1] "学历因子:"
[1] 本科 硕士 本科 博士 本科
Levels: 本科 < 硕士 < 博士
[1] "本科 < 硕士? TRUE"
[1] "按性别平均分:"
男 女
88.0 88.5
R Language Examples