Using stringi package
The stringi package in R is used to carry out string manipulations. It can be downloaded and installed into the working space using the following command :
install.packages("stringi")
The method stri_replace_last() is directly used to replace the last occurrence of the specified pattern in the string. The method has the following syntax :
Syntax: stri_replace_last(str, fixed, replacement)
Arguments :
- str – The string to replace the character in
- fixed – The fixed pattern to look for
- replacement – The string to replace the fixed pattern with
Here, in the last occurrence the character string “,”
R
# installing the reqd libraries library ( "stringi" ) # creating a dummy string str <- "Hi A, B, C" print ( "Input String" ) print (str) # replacing the last comma with # & out_str <- stri_replace_last ( str, fixed = "," , " &" ) # printing the output string print ( "Output String" ) print (out_str) |
Output
[1] "Input String" [1] "Hi A, B, C" [1] "Output String" [1] "Hi A, B & C"
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.