15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Rename Factor Levels in R (With Examples)

How to Rename Factor Levels in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

There are two methods you can use to rename factor levels in R:

Method 1: Use levels() from Base R

levels(df$col_name) new_name1', 'new_name2', 'new_name3')

Method 2: Use recode() from dplyr package

library(dplyr)

data$col_name new_name1', 
                                       name2 = 'new_name2',
                                       name3 = 'new_name3')

The following examples show how to use each of these methods in practice.

Method 1: Use levels() Function

Suppose we have the following data frame in R:

#create data frame
df frame(conf = factor(c('North', 'East', 'South', 'West')),
                 points = c(34, 55, 41, 28))

#view data frame
df

   conf points
1 North     34
2  East     55
3 South     41
4  West     28

#view levels of 'conf' variable
levels(df$conf)

[1] "East"  "North" "South" "West" 

The following code shows how to rename one factor level by name using the levels() function:

#rename just 'North' factor level
levels(df$conf)[levels(df$conf)=='North'] N'

#view levels of 'conf' variable
levels(df$conf)

[1] "East"  "N"     "South" "West"

And the following code shows how to rename every factor level:

#rename every factor level
levels(df$conf) N', 'E', 'S', 'W')

#view levels of 'conf' variable
levels(df$conf)

[1] "N" "E" "S" "W"

Example 2: Use recode() Function

The following code shows how to use the recode() function from the dplyr package to rename factor levels:

library(dplyr)

#create data frame
df frame(conf = factor(c('North', 'East', 'South', 'West')),
                 points = c(34, 55, 41, 28))

#recode factor levels
df$conf N',
                           East  = 'E',
                           South = 'S',
                           West  = 'W')

levels(df$conf)

[1] "E" "N" "S" "W"

Note: You can find the complete documentation for the recode() function here.

Additional Resources

How to Convert Factor to Numeric in R
How to Convert Factor to Character in R
How to Reorder Factor Levels in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories