如何用R中的反斜杠替换符号? [英] How to replace a symbol by a backslash in R?

查看:44
本文介绍了如何用R中的反斜杠替换符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我用 R 中的反斜杠替换一个字符吗?我的试验:

Could you help me to replace a char by a backslash in R? My trial:

gsub("D","\\","1D2")

提前致谢

推荐答案

您需要重新转义反斜杠,因为它需要作为普通 R 字符串的一部分转义一次(因此 '\\' 而不是 '\'),并且另外它在替换模式中由 gsub 处理不同,因此需要再次转义.以下工作:

You need to re-escape the backslash because it needs to be escaped once as part of a normal R string (hence '\\' instead of '\'), and in addition it’s handled differently by gsub in a replacement pattern, so it needs to be escaped again. The following works:

gsub('D', '\\\\', '1D2')
# "1\\2"

结果看起来与期望的输出不同的原因是 R 并没有实际打印结果,它打印了一个可解释的 R 字符串(注意周围的引号!).但是如果你使用 catmessage 它会被正确打印:

The reason the result looks different from the desired output is that R doesn’t actually print the result, it prints an interpretable R string (note the surrounding quotation marks!). But if you use cat or message it’s printed correctly:

cat(gsub('D', '\\\\', '1D2'), '\n')
# 1\2

这篇关于如何用R中的反斜杠替换符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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