避免 R 函数粘贴为引号生成反斜杠 [英] Avoid R function paste generating backslash for quotes

查看:139
本文介绍了避免 R 函数粘贴为引号生成反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将包含引号 ("") 的两个字符串组合为字符/字符串向量或与 R 函数粘贴,以便我可以将结果插入 openxlsx 包.

I am trying to get two strings that contain quotations ("") combined as a character/string vector or with R function paste so I can plug the result in the argument x of writeFormula in openxlsx package.

一个例子是这样的

paste('HYPERLINK("file)',':///"&path!$C$1&TRIM(MID(CELL("filename",B',sep="")

我希望它应该产生这样的结果

and I hope that it should produce the result like this

HYPERLINK("file:///"&path!$C$1&TRIM(MID(CELL("filename",B

但它实际上产生的结果在 ":

but it actually produces the result with a backslash in front of the ":

[1] "HYPERLINK(\"file):///\"&path!$C$1&TRIM(MID(CELL(\"filename\",B"

我搜索了许多可能的解决方案,例如用 cat 替换 paste 或 在 paste 前添加 noquote 函数 但输出不是字符向量.像 toString 或 as.character 这样的函数可以将这些结果转换为字符串,但反斜杠也会回来.

I have searched for many potential solutions like replace paste with cat or add noquote function in front of paste but the output is not a character vector. Functions like toString or as.character could convert these results to strings but the backslash comes back as well.

非常感谢您对此的任何帮助.谢谢.

Really appreciate any helps with this. Thanks.

推荐答案

p 中没有反斜杠.您看到的反斜杠正是 R 显示引号的方式(以便您知道引号是字符串的一部分,而不是结束分隔符)但不在字符串本身中.

There are no backslashes in p. The backslashes you see are just how R displays a quote (so that you know that the quote is part of the string and not the ending delimiter) but are not in the string itself.

p <- paste0('HYPERLINK("file)', ':///"&path!$C$1&TRIM(MID(CELL("filename",B')
p
## [1] "HYPERLINK(\"file):///\"&path!$C$1&TRIM(MID(CELL(\"filename\",B"

# no backslashes are found in p
grepl("\\", p, fixed = TRUE)
## [1] FALSE

noquote(p)cat(p, "\n")writeLines(p) 可用于显示字符串没有反斜杠转义:

noquote(p), cat(p, "\n") or writeLines(p) can be used to display the string without the backslash escapes:

noquote(p)
## [1] HYPERLINK("file):///"&path!$C$1&TRIM(MID(CELL("filename",B

cat(p, "\n")
## HYPERLINK("file):///"&path!$C$1&TRIM(MID(CELL("filename",B 

writeLines(p)
## HYPERLINK("file):///"&path!$C$1&TRIM(MID(CELL("filename",B

可以看到单个字符被这样的空格分隔并且没有反斜杠:

One can see the individual characters iseparated by spaces like this and there are no backslashes:

do.call(cat, c(strsplit(p, ""), "\n"))
## H Y P E R L I N K ( " f i l e ) : / / / " & p a t h ! $ C $ 1 & T R I M ( M I D ( C E L L ( " f i l e n a m e " , B 

这里的另一个例子 p2 包含一个双引号,其中包含一个字符,而不是 2:

As another exmaple here p2 contains one double quote and has a single character in it, not 2:

p2 <- '"'
p2
## [1] "\""

nchar(p2)
## [1] 1

这篇关于避免 R 函数粘贴为引号生成反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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