How do I strip dollar signs ($) from data/ escape special characters in R?

早过忘川 提交于 2019-12-28 02:55:11

问题


I've been using gsub("toreplace","replacement", myvector) to clean out data in R. While this works for commas and the like, removing "$" has no effect. So if I do gsub("$","",myvector) all the dollar signs remain in place.

I think this is because $ is a special character in R. I tried escaping it "\$" but that yields the same result (no effect). And I couldn't find a resource on escaping special characters in R.

Obviously I should do this in preprocessing. But I was wondering if anyone out there knew how to either a) escape special characters in R b) get rid of pesky $ in R directly. For science.


回答1:


You have to escape it twice, first for R, second for the regex.

gsub('\\$', '', c("a$a", "bb$"))
[1] "aa" "bb"

See ?Quotes for details on quoting and escaping.




回答2:


Use fixed = TRUE:

gsub('$', '', c("a$a", "bb$"), fixed = TRUE)

Then you don't need to worry about any special characters. In stringr, this is implemented a little differently:

library(stringr)
str_replace_all(c("$100","ta$ty"), fixed("$"), "")

Thanks to DiggyF and James for the examples!




回答3:


Escaping characters can be a pain some times, but just putting it in square brackets (make it a character class) helps with this:

> gsub("[$]","",c("$100","ta$ty"))
[1] "100"  "taty"


来源:https://stackoverflow.com/questions/6639713/how-do-i-strip-dollar-signs-from-data-escape-special-characters-in-r

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