How to replace total string if partial string matches with another string in R data frame column?

To replace total string if partial string matches with another string in R data frame column, we can follow the below steps −

  • First of all, create a data frame with string column.

  • Then, use gsub function to replace total string if partial string matches with another string.

Example

Create the data frame

Let’s create a data frame as shown below −

String

Output

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

    String
1  south\nafrica3541
2  russia3541
3  sudan1234
4  india1234
5  south\nafrica3541
6  india1234
7  south\nafrica3541
8  korea1234
9  korea1234
10 uk3541
11 india1234
12 korea1234
13 belarus3541
14 belarus3541
15 korea1234
16 china1234
17 sudan1234
18 uk3541
19 india1234
20 korea1234
21 korea1234
22 sudan1234
23 uk3541
24 china1234
25 korea1234

Replace total string if partial string matches

Using gsub function to replace total string with No if 3541 exists in the string as shown below −

String

Output

    String           Replaced_S
1  china1234         china1234
2  korea1234         korea1234
3  russia3541        No
4  sri\nlanka1234    sri\nlanka1234
5  russia3541        No
6  nepal1234         nepal1234
7  korea1234         korea1234
8  russia3541        No
9  sudan1234         sudan1234
10 sudan1234         sudan1234
11 sudan1234         sudan1234
12 south\nafrica3541 No
13 nepal1234         nepal1234
14 nepal1234         nepal1234
15 south\nafrica3541 No
16 nepal1234         nepal1234
17 canada3541        No
18 sri\nlanka1234    sri\nlanka1234
19 china1234         china1234
20 sudan1234         sudan1234
21 south\nafrica3541 No
22 nepal1234         nepal1234
23 china1234         china1234
24 sri\nlanka1234    sri\nlanka1234
25 china1234         china1234
Updated on: 2021-11-11T06:07:51+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements