R, stringr - replace multiple characters from all elements of a vector with a single command

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?

Upvotes: 10

Views: 11827

Answers (1)

C. Braun
C. Braun

Reputation: 5191

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"

Upvotes: 20

Related Questions