lowndrul
lowndrul

Reputation: 3815

Replacing underscore "_" with backslash-underscore "\_" in an R string

Q: How can I replace underscores "_" with backslash-underscores "_" in an R string? I'd prefer to use the stringr package.

Also, can anyone explain why line 5 below fails to get the desired result? I was almost certain that would work.

library(stringr)
s <- "foo_bar_baz"
str_replace_all(s, "_", 5) # [1] "foo5bar5baz"
str_replace_all(s, "_", "\_") # Error: '\_' is an unrecognized escape in character string starting ""\_"
str_replace_all(s, "_", "\\_") # [1] "foo_bar_baz"
str_replace_all(s, "_", "\\\_") # Error: '\_' is an unrecognized escape in character string starting ""\\\_"
str_replace_all(s, "_", "\\\\_") # [1] "foo\\_bar\\_baz"

Context: I'm making a LaTeX table using xtable and need to sanitize my column names since they all have underscores and break LaTeX.

Upvotes: 4

Views: 6607

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

It is all much easier. Replace literal strings with literal strings with the help of fixed("_"), no need for a regex.

> library(stringr)
> s <- "foo_bar_baz"
> str_replace_all(s, fixed("_"), "\\_")
[1] "foo\\_bar\\_baz"

And if you use cat:

> cat(str_replace_all(s, fixed("_"), "\\_"))
foo\_bar\_baz> 

You will see that you actually have 1 backslash in the result.

Upvotes: 4

Related Questions