I have many different characters which have the following structure:
# Example
x <- "char1, char2, char3"
I want to remove the last comma of this character with " &", i.e. the desired output should look as follows:
# Desired output
"char1, char2 & char3"
How could I replace the last comma of a character with " &"?
You can use sub
:
sub(",([^,]*)$"," &\\1", x)
# [1] "char1, char2 & char3"
One option is stri_replace_last
from stringi
library(stringi)
stri_replace_last(x, fixed = ',', ' &')
#[1] "char1, char2 & char3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With