12

I have started learning R and am trying to create vector as below:

c(""check"")

I need the output as : "check". But am getting syntax error. How to escape the quotes while creating a vector?

joran
  • 169,992
  • 32
  • 429
  • 468
knix2
  • 327
  • 1
  • 5
  • 19

3 Answers3

25

As @juba mentioned, one way is directly escaping the quotes.

Another way is to use single quotes around your character expression that has double quotes in it.

> x <- 'say "Hello!"'
> x
[1] "say \"Hello!\""
> cat(x)
say "Hello!"
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
14

Other answers nicely show how to deal with double quotes in your character strings when you create a vector, which was indeed the last thing you asked in your question. But given that you also mentioned display and output, you might want to keep dQuote in mind. It's useful if you want to surround each element of a character vector with double quotes, particularly if you don't have a specific need or desire to store the quotes in the actual character vector itself.

# default is to use "fancy quotes"
text <- c("check")
message(dQuote(text))
## “check”

# switch to straight quotes by setting an option
options(useFancyQuotes = FALSE)
message(dQuote(text))
## "check"

# assign result to create a vector of quoted character strings
text.quoted <- dQuote(text)
message(text.quoted)
## "check"

For what it's worth, the sQuote function does the same thing with single quotes.

regetz
  • 671
  • 3
  • 7
  • how than assign this double quotes string to variable? – Muhammad Usman Saleem Feb 28 '17 at 18:33
  • One thing to be aware of is that dQuote and sQuote may use "smart" or "fancy" quotes in place of plain ASCII quotation mark characters. This may not be what you want if, for example, you are writing to a CSV file. – mhwombat Apr 27 '17 at 11:01
7

Use a backslash :

x <- "say \"Hello!\""

And you don't need to use c if you don't build a vector.

If you want to output quotes unescaped, you may need to use cat instead of print :

R> cat(x)
say "Hello!"
juba
  • 47,631
  • 14
  • 113
  • 118
  • 2
    I've seen the "you don't need `c` if you don't build a vector" thing before, and I know you don't need it, but just curious: does it hurt at all? – A5C1D2H2I1M1N2O1R2T1 Mar 04 '13 at 15:36
  • 2
    No it doesn't hurt, as the result is the same. I think that if you just do `x <- 3` you sort of create a vector of length one, as you can apply vector functions on `x` (such as `length`, `names`...). – juba Mar 04 '13 at 15:40