4

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

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

Thanks in advance

Kostya
  • 1,552
  • 1
  • 10
  • 16
  • @DavidArenburg Correct, the string is used later in Sweave/LaTex as a path – Kostya Jan 07 '15 at 12:23
  • For paths you shouldn’t use backslashes. All modern operating systems support the forward slash as path separator, and using a backslash is **never** the correct option because it does *not* work on most operating systems (essentially it only works on Windows). If you don’t want to use the forward slash (for whatever reason), use the value of `.Platform$file.sep` instead. – Konrad Rudolph Jan 07 '15 at 12:27

3 Answers3

5

When inputting backslashes from the keyboard, always escape 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 output, I'm afraid you can't do that in R (at least in my knowledge). You can use forward slashes in path names to avoid this.

For more information, refer to this issue raised in R help: How to replace double backslash with single backslash in R.

Ujjwal
  • 3,088
  • 4
  • 28
  • 36
5

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
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thanks for the second part. It was driving me crazy why I could only get it to print multiples of 2 backslashes. – le_andrew Feb 21 '19 at 02:42
0
gsub("\\p{S}", "\\\\", text, perl=TRUE);

\p{S} ... Match a character from the Unicode category symbol.

Andie2302
  • 4,825
  • 4
  • 24
  • 43