How to rename the factor levels of a factor variable by using mutate of dplyr package in R?


We know that a factor variable has many levels but it might be possible that the factor levels we have are not in the form as needed. For example, if we want to have capital letters as a factor level but the original data has small letters of English alphabets. In this situation we can rename those factor levels by using mutate of dplyr package.

Example

Consider the below data frame −

City <-rep(c("LA","NY","SF","LV"),each=5)
Temp <-sample(1:50,20)
df1 <-data.frame(City,Temp)
df1

Output

 City Temp
1 LA 2
2 LA 47
3 LA 7
4 LA 24
5 LA 11
6 NY 50
7 NY 9
8 NY 46
9 NY 18
10 NY 13
11 SF 37
12 SF 12
13 SF 8
14 SF 3
15 SF 19
16 LV 28
17 LV 20
18 LV 43
19 LV 1
20 LV 22

Renaming the levels of City variable −

Example

df1%>%mutate(City=recode(City,LA="Los Angeles",NY="New York",SF="San Francisco",LV="Las Vegas"))

Output

City Temp
1 Los Angeles 2
2 Los Angeles 47
3 Los Angeles 7
4 Los Angeles 24
5 Los Angeles 11
6 New York 50
7 New York 9
8 New York 46
9 New York 18
10 New York 13
11 San Francisco 37
12 San Francisco 12
13 San Francisco 8
14 San Francisco 3
15 San Francisco 19
16 Las Vegas 28
17 Las Vegas 20
18 Las Vegas 43
19 Las Vegas 1
20 Las Vegas 22

Let’s have a look at another example −

Example

Grade <-rep(c("A","B","C","D","E"),times=4)
Score <-c(91:94,81:84,61:64,51:54,26:29)
df2 <-data.frame(Grade,Score)
df2

Output

Grade Score
1 A 91
2 B 92
3 C 93
4 D 94
5 E 81
6 A 82
7 B 83
8 C 84
9 D 61
10 E 62
11 A 63
12 B 64
13 C 51
14 D 52
15 E 53
16 A 54
17 B 26
18 C 27
19 D 28
20 E 29

Example

df2%>%mutate(Grade=recode(Grade,A="Excellent",B="Very Good",C="Good",D="Bad",E="Very Bad"))

Output

Grade Score
1 Excellent 91
2 Very Good 92
3 Good 93
4 Bad 94
5 Very Bad 81
6 Excellent 82
7 Very Good 83
8 Good 84
9 Bad 61
10 Very Bad 62
11 Excellent 63
12 Very Good 64
13 Good 51
14 Bad 52
15 Very Bad 53
16 Excellent 54
17 Very Good 26
18 Good 27
19 Bad 28
20 Very Bad 29

Updated on: 21-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements