james
james

Reputation: 27

Unable to enclose double quotes inside string in R

unable to enclose "hey" in double quotes within a string . I am unable to get output as Hey "Hey"

ad<- "hey"
fd<- paste("Hey","",ad,sep="")

Upvotes: 0

Views: 536

Answers (3)

Eyayaw
Eyayaw

Reputation: 1081

You can write raw strings like:

r"{"Hey"}"
r'{"Hey"}'
[1] "\"hey\""

See ?Quotes

Raw character constants are also available using a syntax similar to the one used in C++: r"(...)" with ... any character sequence, except that it must not contain the closing sequence )". The delimiter pairs [] and {} can also be used, and R can be used in place of r. For additional flexibility, a number of dashes can be placed between the opening quote and the opening delimiter, as long as the same number of dashes appear between the closing delimiter and the closing quote.

Upvotes: 0

r2evans
r2evans

Reputation: 161085

The dQuote function is made for this:

dQuote("hey")
# [1] "\"hey\""

Note that depending on the OS and your environment, it might add "fancy quotes" (angled/directional double-quotes). They may look good but if you want to reuse the results as a string in R, it won't work because R does not recognize its smart quotes as string-boundaries. You can explicitly disable it with dQuote(., q=FALSE). (The default is FALSE on windows except for the Rgui console, but I believe the default is TRUE elsewhere.)

Depending on your need, you may also like shQuote due to its escaping of existing embedded quotes:

cat(dQuote('"hey" there'), "\n")
# ""hey" there"                        # may not be right

cat(shQuote('"hey" there'), "\n")
# "\"hey\" there" 

though whether that is correct depends on your needs; shQuote was designed for shell-quoting/escaping.

Ultimately in your example, I think you would use

ad <- "Hey"
paste("Hey", dQuote(ad))
# [1] "Hey \"Hey\""

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389325

Double quotes can be added with

paste0('"', "Hey", '"')
#[1] "\"Hey\""

Or

sprintf('"%s"', "Hey")
#[1] "\"Hey\""

Note that R displays strings with double quotes (") so to show double quotes as part of string it escapes it with backslash \. To see actual string you may use cat on it.

cat(paste0('"', "Hey", '"'))
#"Hey"

Upvotes: 1

Related Questions