44

This is perhaps rather a minor question...

but just a moment ago I was looking through some code I had written and noticed that I tend to just use ="something" and ='something_else' completely interchangeably, often in the same function.

So my question is: Is there R code in which using one or other (single or double quotes) has different behaviour? Or are they totally synonymous?

YaOzI
  • 16,128
  • 9
  • 76
  • 72
Stephen Henderson
  • 6,340
  • 3
  • 27
  • 33

4 Answers4

30

According to http://stat.ethz.ch/R-manual/R-patched/library/base/html/Quotes.html, "[s]ingle and double quotes delimit character constants. They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes."

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
  • thx I didn't know it had a help page. Thats quite clear though I think Jorans example is additional info too. – Stephen Henderson Dec 13 '13 at 17:45
  • 9
    I disagree on the " preference. That requires the shift key, which slows typing and increases hand-strain. I always recommend '. If they are truly interchangeable, that breaks the tie for me. – Bryce Chamberlain Apr 04 '19 at 17:04
  • 1
    @BryceChamberlain, you have a valid point. I sometimes switch to single quotes for that exact reason, but I end up switching back because habit is a bitch. – Waldir Leoncio Apr 05 '19 at 08:32
  • What about HTML popups in R? – Wolkuz Jul 31 '22 at 21:07
19

Just for curiosity, there is a further explaination in R-help mailing list for Why double quote is preferred in R:

To avoid confusion for those who are accustomed to programming in the C family of languages (C, C++, Java), where there is a difference in the meaning of single quotes and double quotes. A C programmer reads 'a' as a single character and "a" as a character string consisting of the letter 'a' followed by a null character to terminate the string.

In R there is no character data type, there are only character strings. For consistency with other languages it helps if character strings are delimited by double quotes. The single quote version in R is for convenience.

(Since) On most keyboards you don't need to use the shift key to type a single quote but you do need the shift for a double quote.

YaOzI
  • 16,128
  • 9
  • 76
  • 72
16
> print(""hi"")
Error: unexpected symbol in "print(""hi"
> print("'hi'")
[1] "'hi'"
> print("hi")
[1] "hi"
user1317221_G
  • 15,087
  • 3
  • 52
  • 78
1
"'hi'" == '"hi"'
[1] FALSE
Donald Seinen
  • 4,179
  • 5
  • 15
  • 40