How to change a text value in an R data frame?


To change a text value in an R data frame, we can simply use replace function.

For Example, if we have a data frame called df that contains a column say Names and one of the names say Raj is misspelled as Raaj then we can replace Raaj with Raj by using the command given below −

df$Names<-replace(df$Names,df$Names=="Raaj","Raj")

Example 1

Following snippet creates a sample data frame −

Gender<-sample(c("Male","Femalee"),20,replace=TRUE)
Gender_dat<-data.frame(Gender)
Gender_dat

The following dataframe is created

  Gender
1  Femalee
2  Male
3  Femalee
4  Male
5  Male
6  Male
7  Femalee
8  Femalee
9  Femalee
10 Male
11 Male
12 Male
13 Femalee
14 Male
15 Femalee
16 Male
17 Femalee
18 Male
19 Male
20 Male

To replace Femalee in df1 with Female on the above created data frame, add the following code to the above snippet −

Gender<-sample(c("Male","Female"),20,replace=TRUE)
Gender_dat<-data.frame(Gender)
Gender_dat$Gender<-
replace(Gender_dat$Gender,Gender_dat$Gender=="Femalee","Female")
Gender_dat

Output

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

   Gender
1  Female
2  Male
3  Female
4  Male
5  Male
6  Male
7  Female
8  Female
9  Female
10 Male
11 Male
12 Male
13 Female
14 Male
15 Female
16 Male
17 Female
18 Male
19 Male
20 Male

Example 2

Following snippet creates a sample data frame −

Transaction<-sample(c("Online","Ofline"),20,replace=TRUE)
Trans_dat<-data.frame(Transaction)
Trans_dat

The following dataframe is created

  Transaction
1  Online
2  Online
3  Online
4  Ofline
5  Ofline
6  Online
7  Ofline
8  Ofline
9  Ofline
10 Ofline
11 Ofline
12 Ofline
13 Online
14 Ofline
15 Online
16 Ofline
17 Online
18 Online
19 Online
20 Online

To replace Ofline in df2 with Offline on the above created data frame, add the following code to the above snippet −

Transaction<-sample(c("Online","Offline"),20,replace=TRUE)
Trans_dat<-data.frame(Transaction)
Trans_dat$Transaction<-
replace(Trans_dat$Transaction,Trans_dat$Transaction=="Ofline","Offline")
Trans_dat

Output

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

  Transaction
1  Online
2  Online
3  Online
4  Offline
5  Offline
6  Online
7  Offline
8  Offline
9  Offline
10 Offline
11 Offline
12 Offline
13 Online
14 Offline
15 Online
16 Offline
17 Online
18 Online
19 Online
20 Online

Updated on: 02-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements