R Factors
Factors are used to store categorical data. For example, gender has two categories, male and female, and age can be divided into minors and adults.
In R, factors are created using the factor() function, with a vector as the input parameter.
The syntax of the factor() function is as follows:
factor(x = character(), levels, labels = levels,
exclude = NA, ordered = is.ordered(x), nmax = NA)
Parameter Description:
- x: a vector.
- levels: specifies the level values. If not specified, they are derived from the distinct values of x.
- labels: labels for the levels. If not specified, the corresponding strings of the level values are used.
- exclude: values to exclude.
- ordered: a logical value specifying whether the levels are ordered.
- nmax: the maximum number of levels.
The following example converts a character vector into a factor:
Example
x
<-
c
(
"male"
,
"female"
,
"male"
,
"male"
,
"female"
)
sex
<-
factor
(
x
)
(
sex
)
(
is.factor
(
sex
)
)
The output of the code above is:
[1] 男 女 男 男 女
Levels: 男 女
[1] TRUE
The following example sets the factor levels to c('male', 'female'):
Example
x
<-
c
(
"male"
,
"female"
,
"male"
,
"male"
,
"female"
,
levels
=
c
(
'male'
,
'female'
)
)
sex
<-
factor
(
x
)
(
sex
)
(
is.factor
(
sex
)
)
The output of the code above is:
levels1 levels2
男 女 男 男 女 男 女
Levels: 男 女
[1] TRUE
Factor Level Labels
Next, we use the labels parameter to add a label to each factor level. The order of characters in the labels parameter must be consistent with the order in the levels parameter. For example:
Example
sex
=
factor
(
c
(
'f'
,
'm'
,
'f'
,
'f'
,
'm'
)
,
levels
=
c
(
'f'
,
'm'
)
,
labels
=
c
(
'female'
,
'male'
)
,
ordered
=
TRUE
)
(
sex
)
The output of the code above is:
[1] female male female female male
Levels: female < male
Generate Factor Levels
We can use the gl() function to generate factor levels. The syntax is as follows:
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
Parameter Description:
- n: set the number of levels
- k: set the number of repetitions for each level
- length: set the length
- labels: set the values of the levels
- ordered: set whether the levels are ordered, a boolean value.
Example
v
<-
gl
(
3
,
4
,
labels
=
c
(
"Google"
,
"Runoob"
,
"Taobao"
)
)
(
v
)
The output of the code above is:
[1] Google Google Google Google Runoob Runoob Runoob Runoob Taobao Taobao
[11] Taobao Taobao
Levels: Google Runoob Taobao