问题
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:
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"
来源:https://stackoverflow.com/questions/48751528/r-stringr-replace-multiple-characters-from-all-elements-of-a-vector-with-a-si