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

|▌冷眼眸甩不掉的悲伤 提交于 2020-08-07 07:55:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!