Escape ’til infinity — removing or replacing backslashes in a string can be burdensome in any programming language, if you’re not familiar what regex library is below the hood. In this post, we’ll remove a backslash from a string in R.
Using gsub, there’s two paradigms to choose from. The first is by selecting it via a regex pattern. Believe it or not, but you’ll have to provide four (!) backslashes. This is because all characters are first parsed by the R parser, before being sent to the command line — i.e. you have to escape the escape.
my_str <- 'I am a \ backslash' my_str <- gsub( pattern = ('\\\\'), replacement = '', x = my_str )
However, there’s a less confusing way. Instead of using regex patterns, you can simply match literal strings by using gsub‘s fixed parameter.
my_str <- gsub( pattern = ('\\'), replacement = '', x = my_str, fixed = T )
You can also do it using stringr:
str_replace(my_str, fixed("\\"), "backslash")
Let me know in the comments below if you figured this out.
By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!