替换下划线“_"带有反斜杠下划线“\_";在 R 字符串中 [英] Replacing underscore "_" with backslash-underscore "\_" in an R string

查看:221
本文介绍了替换下划线“_"带有反斜杠下划线“\_";在 R 字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:如何将 R 字符串中的下划线_"替换为反斜杠下划线_"?我更喜欢使用 stringr 包.

Q: How can I replace underscores "_" with backslash-underscores "_" in an R string? I'd prefer to use the stringr package.

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

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"

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

Context: I'm making a LaTeX table using xtable and need to sanitize my column names since they all have underscores and break LaTeX.

推荐答案

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

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"

如果你使用cat:

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

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

You will see that you actually have 1 backslash in the result.

这篇关于替换下划线“_"带有反斜杠下划线“\_";在 R 字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆