Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R factor() Function - Creating Factors

R factor() Function - Creating Factors

R Language Examples R Language Examples

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:

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"

,

"Doctor"

,

"Bachelor"

)

,

               

levels

=

c

(

"Bachelor"

,

"Master"

,

"Doctor"

)

,

               

ordered

=

TRUE

)

print

(

"Education factor:"

)

print

(

edu

)

print

(

paste

(

"Bachelor < Master?"

, edu

[

1

]

<

edu

[

2

]

)

)

scores

<-

c

(

88

,

92

,

76

,

85

,

90

)

avg_by_gender

<-

tapply

(

scores, gender,

mean

)

print

(

"Average score by gender:"

)

print

(

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 R Language Examples