13

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

3
  • 1
    It seems like there is much interest in this topic. Therefore, I have written an article which summarizes the responses of this thread: statistical-programming.com/… Thanks again for all the great responses! Feb 7, 2019 at 21:28
  • 2
    this is a string not a character, right? Feb 7, 2019 at 23:06
  • 1
    Ah, no, r calls strings characters. Confusing Feb 7, 2019 at 23:32

4 Answers 4

13

One option is stri_replace_last from stringi

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

You can use sub :

sub(",([^,]*)$"," &\\1", x)
# [1] "char1, char2 & char3"
0
3

You could split and unsplit it.

u <- unlist(strsplit(x, ""))
u[tail(grep(",", u), 1)] <- " &"
paste0(u, collapse="")
# [1] "char1, char2 & char3"
0
3

We can also use str_locate_all with str_sub:

library(stringr)
pos <- str_locate_all(x, ',')[[1]][2, ]
str_sub(x, pos[1], pos[2]) <- " &"

# [1] "char1, char2 & char3"
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.