How to create a new level using unique levels of a factor in R data frame?


To create a new level using unique levels of a factor in R data frame, we can follow the below steps −

  • First of all, create a data frame with factor column.
  • Then, create a new level for the unique values in the factor column using table and levels function.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> Factor<-factor(sample(LETTERS[1:15],20,replace=TRUE))
> df<-data.frame(Factor)
> df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Factor
1 O
2 D
3 K
4 M
5 C
6 M
7 K
8 F
9 L
10 H
11 E
12 N
13 O
14 E
15 G
16 H
17 E
18 K
19 K
20 F

Create new level using unique values in factor column

Using levels function with table function to create new level for unique values in the factor column subsetting the column with single square brackets −

 Live Demo

> Factor<-factor(sample(LETTERS[1:15],20,replace=TRUE))
> df<-data.frame(Factor)
> levels(df[,1])[table(df[,1])==1]<-"New_Level"
> df

Output

Factor
1 O
2 New_Level
3 K
4 M
5 New_Level
6 M
7 K
8 F
9 New_Level
10 H
11 E
12 New_Level
13 O
14 E
15 New_Level
16 H
17 E
18 K
19 K
20 F

Updated on: 13-Aug-2021

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements