R Factors

Factors are the R data objects. It is used to categorize the data and store it as levels. They can store both integers and strings. Factors are used in data analysis for statistical modeling. factor() function is used to create factors.

Example 1:

Output:

Example 2:

Output:

Accessing the Elements of a Factor

Accessing elements of a factor is very much similar to that of vectors.

Example:

Output:

How to Modify a Factor

Elements of a factor can be modified using simple assignments. However, we cannot choose values outside of factor’s predefined levels.

Example:

Output:

Changing the Order of Levels

We can change the order of the levels in a factor by applying the factor function again with new order of levels.

Example:

Output:

Generating Factor Levels

To generate factor levels by using the gl() function.  Let’s see the syntax of this gl() function:

Syntax:

Here,

  • n is a number of levels
  • k is the number of replications
  • labels is a vector of labels for the resulting factor levels

Example:

Output:

Reference:
https://www.stat.berkeley.edu/~s133/factors.html