简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM