Reputation: 2147
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 " &"?
Upvotes: 13
Views: 1784
Reputation: 18701
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"
Upvotes: 3
Reputation: 47350
You can use sub
:
sub(",([^,]*)$"," &\\1", x)
# [1] "char1, char2 & char3"
Upvotes: 9
Reputation: 73832
You could split and unsplit it.
u <- unlist(strsplit(x, ""))
u[tail(grep(",", u), 1)] <- " &"
paste0(u, collapse="")
# [1] "char1, char2 & char3"
Upvotes: 3
Reputation: 887981
One option is stri_replace_last
from stringi
library(stringi)
stri_replace_last(x, fixed = ',', ' &')
#[1] "char1, char2 & char3"
Upvotes: 13