0

I am trying to replace the string as shown below. But it is getting duplicated. Can anyone help here

str_replace("A Bring home",c("Bring","home"), c("NEW Bring",'NEW Home'))
[1] "A NEW Bring home" "A Bring NEW Home"

Expected output

str_replace("A Bring home",c("Bring","home"), c("NEW Bring",'NEW Home'))
[1] "A NEW Bring NEW Home" 

As per below suggestions, I tried one example below

reduce2(c("This is the link https://google.com also there is another link, https://yahoo.com This is the link https://google.com"), c("<a href=https://google.com>Click here</a>","<a href=https://yahoo.com>Click here</a>", "<a href=https://google.com>Click here</a>"),  .init = "This is the link https://google.com also there is another link, https://yahoo.com This is the link https://google.com", str_replace)

Output I am getting

This is the link Click here>Click here also there is another link, Click here This is the link https://google.com

Expected ouput

This is the link Click here also there is another link, Click here This is the link Click here
user11740857
  • 502
  • 3
  • 10
  • You are passing vectors to the parameters, so the return values will also be vectors. You need to sequence your `str_replace` values – mikebader Aug 26 '21 at 11:33
  • Can you help me here? please – user11740857 Aug 26 '21 at 11:33
  • 1
    Does this answer your question? [stringr str\_replace on multiple patterns and replacements?](https://stackoverflow.com/questions/60129058/stringr-str-replace-on-multiple-patterns-and-replacements) – mnist Aug 26 '21 at 11:34
  • 1
    You can use a capture group with `string_replace_all()` - `str_replace_all("A Bring home",c("(Bring|home)"), c("NEW \\1"))`. – Ritchie Sacramento Aug 26 '21 at 11:35
  • I think that @mnist's answer is correct for the best way to do this. – mikebader Aug 26 '21 at 11:38
  • What about: `str_replace("A Bring home", "Bring", "NEW Bring NEW")` – TarJae Aug 26 '21 at 11:47
  • This command would also work, and will be especially useful if your replacement depends on the pattern: `str_replace_all("A Bring home", c("Bring" = "NEW Bring", "home" = "NEW home"))`. – Vincent Guillemot Aug 26 '21 at 11:47
  • @mnist thanks. Your suggestion worked. But Not sure why for this example, I am not getting properly. ````reduce2(c("https://google.com", "https://yahoo.com", "https://google.com"), c("Click here","Click here", "Click here"), .init = "https://google.com, https://yahoo.com,https://google.com", str_replace) ```` – user11740857 Aug 26 '21 at 13:34
  • please update your question with the actual example including expected outcome – mnist Aug 26 '21 at 13:38
  • I get the error `Error in reduce2_impl(.x, .y, .f, ..., .init = .init, .left = TRUE) : `.y` does not have length 1`. Additionally, please format your code with some line breaks – mnist Aug 26 '21 at 18:32

0 Answers0