Replace numerical column values based on character column values in R data frame.


To replace numerical column values based on character column values in R data frame, we can use subsetting with single square brackets and %in% operator and the value will be assigned with <-.

To understand how it can be done check out the Examples given below −

Example 1

Following snippet creates a sample data frame −

Class<-sample(c("First","Second","Third"),20,replace=TRUE)
Score<-sample(1:100,20)
df1<-data.frame(Class,Score)
df1

The following dataframe is created

   Class  Score
 1 Second 25
 2 First  11
 3 Second 63
 4 Third  77
 5 Third  62
 6 Third  26
 7 First  83
 8 Third  57
 9 First  15
10 Third  16
11 Second  7
12 First  87
13 First  35
14 First  91
15 First  40
16 Second 60
17 Second 81
18 Second 75
19 Second 56
20 Second 32

To replace values corresponding to “Third” in Class to 35 in Score on the above created data frame, add the following code to the above snippet −

Class<-sample(c("First","Second","Third"),20,replace=TRUE)
Score<-sample(1:100,20)
df1<-data.frame(Class,Score)
df1$Score[df1$Class %in% "Third"]<-35
df1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

   Class Score
 1 Second 25
 2 First  11
 3 Second 63
 4 Third  35
 5 Third  35
 6 Third  35
 7 First  83
 8 Third  35
 9 First  15
10 Third  35
11 Second  7
12 First  87
13 First  35
14 First  91
15 First  40
16 Second 60
17 Second 81
18 Second 75
19 Second 56
20 Second 32

Example 2

Following snippet creates a sample data frame −

Country<-sample(c("UK","UK","USA","Japan","India"),20,replace=TRUE)
Ranks<-sample(1:5,20,replace=TRUE)
df2<-data.frame(Country,Ranks)
df2

The following dataframe is created

 Country Ranks
 1 Japan 3
 2 Japan 3
 3 India 2
 4 India 3
 5 Japan 2
 6 UK    1
 7 Japan 5
 8 UK    5
 9 UK    1
10 UK    4
11 India 4
12 USA   1
13 UK    2
14 UK    5
15 USA   1
16 Japan 3
17 UK    1
18 India 4
19 Japan 3
20 Japan 5

To replace values corresponding to “India” and “Japan” in Country to 3 in Ranks on the above created data frame, add the following code to the above snippet −

Country<-sample(c("UK","UK","USA","Japan","India"),20,replace=TRUE)
Ranks<-sample(1:5,20,replace=TRUE)
df2<-data.frame(Country,Ranks)
df2$Ranks[df2$Country %in% c("India","Japan")]<-3
df2

Output

If you execute all the above given snippets as a single program, it generates the following Output −

Country Ranks
 1 Japan 3
 2 Japan 3
 3 India 3
 4 India 3
 5 Japan 3
 6 UK    1
 7 Japan 3
 8 UK    5
 9 UK    1
10 UK    4
11 India 3
12 USA   1
13 UK    2
14 UK    5
15 USA   1
16 Japan 3
17 UK    1
18 India 3
19 Japan 3
20 Japan 3

Updated on: 09-Nov-2021

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements