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

R Factors

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:

The following example converts a character vector into a factor:

Example

x

<-

c

(

"male"

,

"female"

,

"male"

,

"male"

,  

"female"

)

sex

<-

factor

(

x

)

print

(

sex

)

print

(

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

)

print

(

sex

)

print

(

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

)

print

(

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:

Example

v

<-

gl

(

3

,

4

,

labels

=

c

(

"Google"

,

"Runoob"

,

"Taobao"

)

)

print

(

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