[R] Definition of = vs. <-

Duncan Murdoch murdoch at stats.uwo.ca
Wed Apr 1 16:55:27 CEST 2009


On 4/1/2009 10:38 AM, Stavros Macrakis wrote:
> NOTA BENE: This email is about `=`, the assignment operator (e.g. {a=1}
> which is equivalent to { `=`(a,1) } ), not `=` the named-argument syntax
> (e.g. f(a=1), which is equivalent to
> eval(structure(quote(f(1)),names=c('','a'))).
> 
> As far as I can tell from the documentation, assignment with = is precisely
> equivalent to assignment with <-.  Yet they call different primitives:

The parser does treat them differently:

 > if (x <- 2) cat("assigned\n")
assigned
 > if (x = 2) cat("assigned\n")
Error: unexpected '=' in "if (x ="

The ?"=" man page explains this:

" The  operator '<-' can be used anywhere,
      whereas the operator '=' is only allowed at the top level (e.g.,
      in the complete expression typed at the command prompt) or as one
      of the subexpressions in a braced list of expressions. "

though the restriction on '=' seems to be described incorrectly:

 > if ((x = 2)) cat("assigned\n")
assigned

in which the assignment is in parentheses, not a braced list.

As to the difference between the operations of the two primitives:  see 
do_set in src/main/eval.c.  The facility is there to distinguish between 
them, but it is not used.

Duncan Murdoch


> 
>> `=`
> .Primitive("=")
>> `<-`
> .Primitive("<-")
> 
> (Perhaps these are different names for the same internal function?)
> 
> Also, the difference is preserved by the parser:
> 
>> quote({a=b})
> {
>     a = b
> }
>> quote({a<-b})
> {
>     a <- b
> }
> 
> even though in other cases the parser canonicalizes variant syntax, e.g. ->
> to <-:
> 
>> quote({a->b})
> {
>     b <- a
> }
>> `->`
> Error: object "->" not found
> 
> Is there in fact some semantic difference between = and <- ?
> 
> If not, why do they use a different operator internally, each calling a
> different primitive?
> 
> Or is this all just accidental inconsistency resulting from the '=', '<-',
> and '->' features being added at different times by different people working
> off different stylistic conventions?
> 
>             -s
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list