0

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"
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
David Z
  • 6,641
  • 11
  • 50
  • 101
  • I think this is something like this old question - https://stackoverflow.com/questions/26171318/regex-for-preserving-case-pattern-capitalization/26171700 - a basic for loop running through each possibility should do it. `for (i in c) {s <- gsub(sub("-"," ", i), i, s)}` – thelatemail Apr 08 '19 at 00:17
  • 1
    Possible duplicate of [Replace multiple strings in one gsub() or chartr() statement in R?](https://stackoverflow.com/questions/33949945/replace-multiple-strings-in-one-gsub-or-chartr-statement-in-r) – BENY Apr 08 '19 at 00:22

1 Answers1

2

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)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68