How to use sub() function In R Language

We can replace only the first occurrence of a particular character using sub() function, it will replace only the first occurrence character in the string

Syntax: sub(character,new_character, string)

Parameters:

  • string is the input string
  • character is the character present in the string to be replaced
  • new_character is the new character to be placed in the place in the existing character

Example: R program to replace character in a string using sub() function

R




# consider a string "Hello Geek"
# replace the character 'e' in  "Hello Geek" 
# with "E"
print(sub("e", "E", "Hello Geek") )
  
# consider a string "Python and java"
# replace the character 'a' in  "Python and java"
# with "M"
print(sub("a", "M", "Python and java") )


Output:

[1] "HEllo Geek"
[1] "Python Mnd java"

Replace Specific Characters in String in R

In this article, we will discuss how to replace specific characters in a string in R Programming Language.

Similar Reads

Method 1: Using gsub() function

We can replace all occurrences of a particular character using gsub() function....

Method 2: Using sub() function

...

Method 3: Using str_replace_all() function

We can replace only the first occurrence of a particular character using sub() function, it will replace only the first occurrence character in the string...

Method 4: Using str_replace() function

...

Contact Us