Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are " preferred over ' in R

Tags:

string

r

From help("'"):

Single 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.

If they are interchangeable, why are double quotes preferred? I've yet to find a difference between them in my own usage. Particularly surprising is that mixed character vectors are allowable:

> c("a",'b',"c")
[1] "a" "b" "c"

Edit

I'm really asking two questions here, I guess:

  1. Are there any situations in which ' and " behave differently?
  2. If not, why was " chosen as the preferred version by convention?

Answers so far have been related to (2), but (1) is at least as much of-interest.

like image 314
Ari B. Friedman Avatar asked Nov 30 '12 02:11

Ari B. Friedman


1 Answers

I do not know of any cases where single-quotes are different than doubles. I think the preference is due to readability and to avoid potential confusion of single quotes with back-ticks which are handled differently. It's probably very hard for the eye-brain system in the wetware to pick up a mismatched back-tick paired with a single quote.

> `newfn` <- function() {}
> newfn
function() {}
> "newfn" <- function() {}
> newfn
function() {}
> 'newfn' <- function() {}
> newfn
function() {}
> var <- c(`a`, "b", 'c')
Error: object 'a' not found
> var <- c( "b", 'c')
> var
[1] "b" "c"
> a <- 1
> identical(`a`, a)
[1] TRUE

So for assignment to names, they (s-quotes, d-quotes, and back-ticks) are all handled the same on the LHS of assignment from function, but the unquoted a and the back-ticked a are the same on the command line and are different than either of the quoted "a" or 'a'.

The other situation where there may be a difference is in data input. Persons' names may have single quotes and it not case you may want to review the handling of the two different kinds of quotes by the read.table function. By default it uses both types of quotes, but it may be necessary to "turn off" the quoting action of single quotes by setting quote="\"" so that you don't get big blobs of data turned into a single text field by mistake. The count.fields function has the same defaults as read.table, so it makes sense to do a preliminary run with this to check for shortened lines cause by mismatched single quotes:

 table( count.fields('filnam.ext') )
like image 85
IRTFM Avatar answered Oct 09 '22 14:10

IRTFM