How do I replace a character with a backslash in R?
You need to re-hide the backslash because it needs to be escaped once as part of a normal R string (hence '\\'
instead of '\'
), and furthermore, it is handled differently on the gsub
in-replace pattern, so it needs to be escaped again. The following works:
gsub('D', '\\\\', '1D2')
# "1\\2"
The reason the result looks different from the desired result is because R does not actually output the result, it prints the interpreted string R (note the surrounding quotes!). But if you use cat
or message
, it printed it correctly:
cat(gsub('D', '\\\\', '1D2'), '\n')
# 1\2
source to share
When entering backslashes from the keyboard, always avoid them:
gsub("D","\\\\","1D2")
#[1] "1\\2"
or,
gsub("D","\\","1D2", fixed=TRUE)
#[1] "1\\2"
or,
library(stringr)
str_replace("1D2","D","\\\\")
#[1] "1\\2"
Note: If you want something like "1\2"
as an output, I'm afraid you can't do it in R (at least as far as I know). To avoid this, you can use forward slashes in path names.
For more information, see the question raised in the R help:. How do I replace the double backslash one backslash in the R .
source to share