R Factor

Factors are used to store categorical data types. For example, a person's 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, taking a vector as the input parameter.

Syntax format of the factor() function:

factor(x = character(), levels, labels = levels,
       exclude = NA, ordered = is.ordered(x), nmax = NA)

Parameter description:

  • x: vector.
  • levels: specify the level values. If not specified, they are obtained from the distinct values of x.
  • labels: labels of the levels. If not specified, the corresponding strings of the level values are used.
  • exclude: characters to exclude.
  • ordered: a logical value used to specify whether the levels are ordered.
  • nmax: the upper limit of the number of levels.

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 running the above code is:

[1] 男 女 男 男 女
Levels: 男 女
[1] TRUE

The following example sets the factor levels toc('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 running the above code is:

levels1 levels2 
男      女      男      男      女      男      女 
Levels: 男 女
[1] TRUE

Factor Level Labels

Next, we use the labels parameter to add labels to each factor level. The character order of the labels parameter must be consistent with the character order of 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 running the above code is:

[1] female male   female female male  
Levels: female < male

Generate Factor Levels

We can usegl()a function to generate factor levels, and the syntax format 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 of 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", "Example","Taobao"))
print(v)

The output of running the above code is:

 [1] Google Google Google Google Example Example Example Example Taobao Taobao
[11] Taobao Taobao
Levels: Google Example Taobao
Other extensions