How to display text with Quotes in R?

46,585

Solution 1

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!"

Solution 2

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.

Solution 3

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!"
Share:
46,585
knix2
Author by

knix2

Updated on July 09, 2022

Comments

  • knix2
    knix2 almost 2 years

    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?

  • A5C1D2H2I1M1N2O1R2T1
    A5C1D2H2I1M1N2O1R2T1 about 11 years
    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?
  • juba
    juba about 11 years
    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...).
  • Muhammad Usman Saleem
    Muhammad Usman Saleem about 7 years
    how than assign this double quotes string to variable?
  • mhwombat
    mhwombat almost 7 years
    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.