Replacing underscore “_” with backslash-underscore “\_” in an R string

谁说我不能喝 提交于 2019-12-10 21:13:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!