David Z
David Z

Reputation: 7041

How to substitute multiple characters in a string in R?

Suppose I have a string such like:

s <- "a bc de fg hij klmn 123 45 789"

And a vector of characters:

c <- c("a-b", "g-h", "j-k", "x-z", "y-5", "3-4")

what I wanted is substitute character such like "a b" in s with characters in c's "a-b". A desired output would be:

new_s<-"a-bc de fg-hij-klmn 123-45 789"

Upvotes: 0

Views: 1692

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

A option is to use gsubfn

library(gsubfn)
gsubfn("\\w\\s\\w", setNames(as.list(c), sapply(c, function(x) gsub("-", " ", x))), s)
#[1] "a-bc de fg-hij-klmn 123-45 789"

Explanation: We match \\w\\s\\w and replace them with patterns specified in the list

setNames(as.list(c), sapply(c, function(x) gsub("-", " ", x)))
#$`a b`
#[1] "a-b"
#
#$`g h`
#[1] "g-h"
#
#$`j k`
#[1] "j-k"
#
#$`x z`
#[1] "x-z"
#
#$`y 5`
#[1] "y-5"
#
#$`3 4`
#[1] "3-4"

Or even shorter (thanks to @Wen-Ben)

gsubfn("\\w\\s\\w", setNames(as.list(c), gsub("-", " ", c)), s)

Upvotes: 2

Related Questions