问:如何在 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 表并且需要清理我的列名,因为它们都有下划线并破坏了 LaTeX。
最佳答案
这一切都容易得多。在 fixed("_")
的帮助下用文字字符串替换文字字符串,不需要正则表达式。
> 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 个反斜杠。
关于用 R 字符串中的反斜杠下划线 "_"替换下划线 "\_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40351980/