In R, why do style guides recommend that one only use double quotes? - r

The lintr package has a check for single-quoted strings, and single quotes are discouraged elsewhere (e.g. ?Quotes). Single and double quoted strings work identically in R, so is there a reason why single quotes are considered bad practice?
Citations to canonical documents especially welcome. To be clear: I'm asking about the reasons given by the R core team for discouraging single quotes; not about people's own opinions on the topic.

I guess because R by default prints using double quotes.
This way the 'other quote character' in a string gets
a) handled normally if its a single quote
b) escaped when its a double quote
when printing. Using double-quotes discourages the use of double-quotes in a string.
Take the following example:
Double Quoted
"It's my car"
Prints
"It's my car"
Single Quoted
'It"s my car'
Prints
"It\"s my car"

Related

Regular expression

I have a document, and I need to find all the words(no spaces) borded with '. (e.g. 'apple', 'hello') What would be the regular expression?
I've tried ^''$ but it didn't work.
If there isn't any solution, it could not be "any word" but also it can be a word from an order(e.g. apple, banana, lemon) but it still must have the (')s.
Thank you so much
Andrew
If you want to capture single-quoted strings, literally any character run except single-quotes but between the single-quotes, use
/'[^']+'/
If you need single words, i.e. alphabetic characters but no spaces, try
/'[a-zA-Z]+'/
I'm asssuming a couple things here:
You're using a language that delimits regexes with slashes. This includes Javascript and Perl to my knowledge, and probably a bunch of others. In some other languages, like C#, you should use double quotes to delimit, e.g. "'[a-zA-Z]+'"
You're using a flavor of regex that does not need to escape the plus sign.
You're trying to capture all such words within a long string. I.e., if the input string is "Here is a 'long' string with 'some' 'words' single-quoted" then you will capture three words: 'long','some', and 'words'.

How to remove "\" from paste function output with quotation marks?

I'm working with the following code:
Y_Columns <- c("Y.1.1")
paste('{"ImportId":"', Y_Columns, '"}', sep = "")
The paste function produces the following output:
"{\"ImportId\":\"Y.1.1\"}"
How do I get the paste function to omit the \? Such that, the output is:
"{"ImportId":"Y.1.1"}"
Thank you for your help.
Note: I did do a search on SO to see if there were any Q's that asked "what is an escape character in R". But I didn't review all the 160 answers, only the first 20.
This is one way of demonstrating what I wrote in my comment:
out <- paste('{"ImportId":"', Y_Columns, '"}', sep = "")
out
#[1] "{\"ImportId\":\"Y.1.1\"}"
?print
print(out,quote=FALSE)
#[1] {"ImportId":"Y.1.1"}
Both R and regex patterns use escape characters to allow special characters to be displayed in print output or input. (And sometimes regex patterns need to have doubled escapes.) R has a few characters that need to be "escaped" in certain situation. You illustrated one such situation: including double-quote character inside a result that will be printed with surrounding double-quotes. If you were intending to include any single quotes inside a character value that was delimited by single quotes at the time of creation, they would have needed to be escaped as well.
out2 <- '\'quoted\''
nchar(out2)
#[1] 8 ... note that neither the surround single-quotes nor the backslashes get counted
> out2
[1] "'quoted'" ... and the default output quote-char is a double-quote.
Here's a good Q&A to review:How to replace '+' using gsub() function in R
It has two answers, both useful: one shows how to double escape a special character and the other shows how to use teh fixed argument to get around that requirement.
And another potentially useful Q&A on the topic of handling Windows paths:
File path issues in R using Windows ("Hex digits in character string" error)
And some further useful reading suggestions: Look at the series of help pages that start with capital letters. (Since I can never remember which one has which nugget of essential information, I tried ?Syntax first and it has a "See Also" list of essential reading: Arithmetic, Comparison, Control, Extract, Logic, NumericConstants, Paren, Quotes, Reserved. and I then realized what I wanted to refer you to was most likely ?Quotes where all the R-specific escape sequence letters should be listed.

Nesting more than two types of quotes in R

I would like to know how to accommodate more than two types of quotes in a same row in R. Let´s say that I want to print:
'first-quote-type1 "first-quote-type2 "second-quote-type2
'sencond-quote-type1
Using one quote in the beginning and one in the end we have:
print("'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1")
Error: unexpected symbol in "print("'first-quote-type1 "first"
I tried to include triple quotes as required in Python in this cases:
print(''''first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1''')
print("""'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1""")
However, I also got a similar error. Some idea how to make this syntax work in R?
To use a quote within a quote you can escape the quote character with a backslash
print("the man said \"hello\"")
However, the print function in R will always escape character.
To not show the escaped character use cat() instead
so...
cat("the man said \"hello\"") will return
the man said "hello"

Are double "" and single '' quotes (always) interchangeable in R?

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?
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."
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.
> print(""hi"")
Error: unexpected symbol in "print(""hi"
> print("'hi'")
[1] "'hi'"
> print("hi")
[1] "hi"

Escaping backslash (\) in string or paths in R

Windows copies path with backslash \, which R does not accept. So, I wanted to write a function which would convert \ to /. For example:
chartr0 <- function(foo) chartr('\','\\/',foo)
Then use chartr0 as...
source(chartr0('E:\RStuff\test.r'))
But chartr0 is not working. I guess, I am unable to escape /. I guess escaping / may be important in many other occasions.
Also, is it possible to avoid the use chartr0 every time, but convert all path automatically by creating an environment in R which calls chartr0 or use some kind of temporary use like using options
From R 4.0.0 you can use r"(...)" to write a path as raw string constant, which avoids the need for escaping:
r"(E:\RStuff\test.r)"
# [1] "E:\\RStuff\\test.r"
There is a new syntax for specifying raw character constants similar to the one used in C++: r"(...)" with ... any character sequence not containing the sequence )". This makes it easier to write strings that contain backslashes or both single and double quotes. For more details see ?Quotes.
Your fundamental problem is that R will signal an error condition as soon as it sees a single back-slash before any character other than a few lower-case letters, backslashes themselves, quotes or some conventions for entering octal, hex or Unicode sequences. That is because the interpreter sees the back-slash as a message to "escape" the usual translation of characters and do something else. If you want a single back-slash in your character element you need to type 2 backslashes. That will create one backslash:
nchar("\\")
#[1] 1
The "Character vectors" section of _Intro_to_R_ says:
"Character strings are entered using either matching double (") or single (') quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using \ as the escape character, so \ is entered and printed as \, and inside double quotes " is entered as \". Other useful escape sequences are \n, newline, \t, tab and \b, backspace—see ?Quotes for a full list."
?Quotes
chartr0 <- function(foo) chartr('\\','/',foo)
chartr0('E:\\RStuff\\test.r')
You cannot write E:\Rxxxx, because R believes R is escaped.
The problem is that every single forward slash and backslash in your code is escaped incorrectly, resulting in either an invalid string or the wrong string being used. You need to read up on which characters need to be escaped and how. Take a look at the list of escape sequences in the link below. Anything not listed there (such as the forward slash) is treated literally and does not require any escaping.
http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants

Resources