truf
truf

Reputation: 3111

replace with gsub in R

I would like to convert string \\xAB\\xAC to \xAB\xACin R.

When I'm using gsub("\\\\", "$", x) I'm getting $AB$AC which is expectable.
But when I'm using gsub("\\\\", "\\", x) I'm getting only ABAC.
Is where a way to workaround this?

Upvotes: 1

Views: 571

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

As per akrun's comment, you can use cat(x) to see/view the 'single' backslashed strings. The reason is that a single literal backslash is represented with two inside the R string literal. cat will "unescape" the string.

To double a single literal backslash, use

x <- "\\ backslash doubled here"
cat(gsub("\\\\", "\\\\\\\\", x), collapse="\n")
# => \\ backslash doubled here 
cat(gsub("\\", "\\\\", x, fixed=TRUE), collapse="\n")
# => \\ backslash doubled here 

See the R demo.

Upvotes: 1

Related Questions