Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a symbol by a backslash in R?

Tags:

regex

r

Could you help me to replace a char by a backslash in R? My trial:

gsub("D","\\","1D2")

Thanks in advance

like image 892
Kostya Avatar asked Dec 25 '22 00:12

Kostya


1 Answers

You need to re-escape the backslash because it needs to be escaped once as part of a normal R string (hence '\\' instead of '\'), and in addition it’s handled differently by gsub in a replacement 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 output is that R doesn’t actually print the result, it prints an interpretable R string (note the surrounding quotation marks!). But if you use cat or message it’s printed correctly:

cat(gsub('D', '\\\\', '1D2'), '\n')
# 1\2
like image 119
Konrad Rudolph Avatar answered Jan 12 '23 00:01

Konrad Rudolph