📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Factors and Levels

A factor is a data structure which is used to represent categorical data. It stores a vector of values along with their unique categories (levels).

Examples of categorical data are:

  • Gender: Male, Female
  • Music: Rock, Pop, Classic, Jazz
  • Result: Pass, Fail
  • Temperature: Low, Medium, High

Creating a Factor

To create a factor in R, you need to use the function called factor(). The argument to this factor() function is a vector.

Syntax:

fact <- factor(vector)

Example:

# Vector
> gender <- c("Male", "Female", "Male", "Male", "Female", "Male")

# Factor
> gen_factor <- factor(gender)
> print(gen_factor)

Output:

[1] Male   Female Male   Male   Female Male  
Levels: Female Male

Levels in Factors

Levels in a factor are the unique categorical values that are recognized by R. By default, R arranges them in alphabetical order, but you can change this manually.

The levels() function is used to get the levels from the factor and to rename/change the levels in the factor.

Example:

# To get the levels
> levels(gen_factor)

Output:

[1] "Female" "Male"  
# To change/rename the levels
> levels(gen_factor) <- c("F", "M")

# Updated levels
> levels(gen_factor)

Output:

[1] "F" "M"
# factor with updated levels
> print(gen_factor)

Output:

[1] M F M M F M
Levels: F M

Note: The new names are given in the order of the existing levels (Female, Male), so Female becomes F and Male becomes M.

Structure of a Factor

To see the internal structure of a factor, use the str() function.

Example:

> str(gen_factor)

Output:

 Factor w/ 2 levels "F","M": 2 1 2 2 1 2

Internally, R stores a factor as integer codes (here 1 for F and 2 for M) together with the levels.

Length of a Factor

To find the length of a factor, use the length() function.

Example:

> print(length(gen_factor))

Output:

[1] 6

The length of a factor is still determined by the length of the data instead of being based on the number of levels.