在 R 字符串中用反斜杠下划线“\_”替换下划线“_”

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

问:如何将 R 字符串中的下划线“_”替换为反斜杠下划线“_”?我更愿意使用 stringr 包。

另外,谁能解释一下为什么下面第 5 行没有得到想要的结果?我几乎可以肯定那会奏效。

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"

上下文:我正在使用 xtable 制作 LaTeX table 并且需要清理我的列名,因为它们都有下划线并破坏 LaTeX。

这一切都容易多了。在 fixed("_") 的帮助下将 literal 字符串替换为 literal 字符串,不需要正则表达式。

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

如果你使用 cat:

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

您会看到结果中实际上有 1 个反斜杠。