问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/40351980/replacing-underscore-with-backslash-underscore-in-an-r-string