i

R Programming Complete Tutorial

Manage Factor levels

In this section, first, we change the levels of the factor, then generate new factor levels.

Change the levels:

In this example, the department contains a vector of four character elements. Factor () function converts this to factor data into levels Finance, IT, HR, and Marketing.  They have organized in ascending order. If we want to arrange the level s according to a specific order, we have to mention the levels at the time of creating the factor.

Generating Factor Levels:

We can generate factor levels using the gl() function where argument n means the number of levels, k means the number of replications and labels is a vector of labels. In the following example, we want to generate a factor of three levels with the label ab, a, and b, and it will be replicated four times.