Joachim Schork
Joachim Schork

Reputation: 2147

Replace last comma in character with " &"

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

Answers (4)

acylam
acylam

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

moodymudskipper
moodymudskipper

Reputation: 47350

You can use sub :

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

Upvotes: 9

jay.sf
jay.sf

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

akrun
akrun

Reputation: 887981

One option is stri_replace_last from stringi

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

Upvotes: 13

Related Questions