Leon
Leon

Reputation: 55

Avoid R function paste generating backslash for quotes

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.

An example is like this

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"

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.

Upvotes: 4

Views: 10145

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269371

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") 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 separated by spaces like this. We see that 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 

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

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

nchar(p2)
## [1] 1

Upvotes: 16

Related Questions