Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

escaping

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.

like image 604
araneae Avatar asked Jul 10 '11 06:07

araneae


People also ask

How do I remove dollar signs from data in R?

Dollar signs can also be removed from a dataframe column or row, by using the gsub() method. All the instances of the $ sign are removed from the entries contained within the data frame.

How do I remove the dollar sign from the comma in R?

You can easily remove dollar signs and commas from data frame columns in R by using gsub() function.

How do you deal with special characters in R?

To be able to use special characters within a function such as gsub, we have to add two backslashes (i.e. \\) in front of the special character. …the next R syntax replaces the question mark… Looks good! We can use the previous type of R code for basically any special character.


2 Answers

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.

like image 94
SiggyF Avatar answered Sep 26 '22 21:09

SiggyF


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!

like image 33
hadley Avatar answered Sep 22 '22 21:09

hadley