How to usesub() method in R Language

The sub() method in R is used to replace the specified part of the string with a new string. The usage of the sub() method is compatible with the regular expressions as well,. It has the following syntax : 

Syntax: sub(search, replacement, str)

Arguments : 

  • search – The search term to look into the string
  • replacement – The new string to replace the search term with
  • str – The string to carry out the replacement in

R




# creating a dummy string 
str <- "Hi Neena, Reena, Teena"
print("Input String")
print(str)
  
# replace the last comma with &
out_str <- sub(",([^,]*)$", " &\\1", str) 
print("Output String")
print(out_str)


Output

[1] "Input String"
[1] "Hi Neena, Reena, Teena"
[1] "Output String"
[1] "Hi Neena, Reena & Teena"

Replace Last Comma in Character with &-Sign in R

A string in R is a sequence of characters which contains numbers, characters, and special symbols. The characters can be modified, inserted as well as deleted in the strings. R provides a large variety of functions and external packages to carry out the string amendments. In this article, we are going to see that how to Replace Last Comma in Character with &-Sign in R Programming Language.

Similar Reads

Method 1 : Using sub() method

The sub() method in R is used to replace the specified part of the string with a new string. The usage of the sub() method is compatible with the regular expressions as well,. It has the following syntax :...

Method 2: Using stringr package

...

Method 3:  Using stringi package

The stringr package in R is used to carry out string manipulations. It can be downloaded and installed into the working space using the following command :...

Method 4: Using in-built string methods

...