How to create a factor in R?

Overview

A factor in R is used to categorize data. For example:

  • Temperature: Cold/Hot
  • Sex: Male/Female
  • Height: Tall/Average/Short

The above are simple examples of factors.

Creating a factor in R

To create a factor in R, we make use of the factor() function.

Syntax

factor(level(s))

Parameter value

The factor() function takes the level(s) corresponding to the factor variable as its parameters.

Return value

The factor() function returns an object class factor.

Code example

# creating a factor
Height <- factor(c("Tall", "Average", "Short"))
# printing the factor
Height

Code explanation

  • Line 2: We create a factor variable Height using the factor() function.
  • Line 5: We print the factor object Height.

Printing only the levels of the factor

To print only the levels corresponding to a factor variable, we use the levels() function.

Syntax

levels(factor)

Parameter value

The levels() function takes the factor variable as its single parameter value.

Code example

# creating a factor
Height <- factor(c("Tall", "Average", "Short", "Average", "Short"))
# printing the levels
levels(Height)