Replace last comma in character with “ &”

  • A+

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 " &"?


One option is stri_replace_last from stringi

library(stringi) stri_replace_last(x, fixed = ',', ' &') #[1] "char1, char2 & char3" 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: