8

First, I am new to R and programming in general, so I apologise if this turns out to be a stupid question.

I have a character vector similar to this:

> vec <- rep(c("XabcYdef", "XghiYjkl"), each = 3)
> vec
[1] "XabcYdef" "XabcYdef" "XabcYdef" "XghiYjkl" "XghiYjkl" "XghiYjkl"

Using the stringr package, I would like to drop the leading "X" and replace the "Y" with a "-".

I have tried the following code, but the result is not what I was hoping for. It looks like the pattern and replacement arguments get recycled over the input vector:

> str_replace(vec, c("X", "Y"), c("", "-"))
[1] "abcYdef"  "Xabc-def" "abcYdef"  "Xabc-def" "abcYdef"  "Xabc-def"

I can achieve the desired result calling the function 2 times:

> vec <- rep(c("XabcYdef", "XghiYjkl"), each = 3)
> vec <- str_replace(vec, "X", "")
> vec <- str_replace(vec, "Y", "-")
> vec
[1] "abc-def" "abc-def" "abc-def" "ghi-jkl" "ghi-jkl" "ghi-jkl"

Is there a way achieve the same with a single command?

1 Answers1

18

str_replace_all can take a vector of matches to replace:

str_replace_all(vec, c("X" = "", "Y" = "-"))
[1] "abc-def" "abc-def" "abc-def" "ghi-jkl" "ghi-jkl" "ghi-jkl"
C. Braun
  • 5,061
  • 19
  • 47
  • Just a word of caution: I was led astray by this answer. If it isn't working for you, take a look at https://stackoverflow.com/questions/61262340/why-is-str-extract-only-catching-some-of-these-values – Amanda Apr 17 '20 at 21:12