[R] advice/opinion on "<-" vs "=" in teaching R

Deepayan Sarkar deepayan.sarkar at gmail.com
Fri Jan 15 10:29:16 CET 2010


On Fri, Jan 15, 2010 at 2:38 PM, Ted Harding
<Ted.Harding at manchester.ac.uk> wrote:
> On 15-Jan-10 08:14:04, Barry Rowlingson wrote:
>> On Fri, Jan 15, 2010 at 6:57 AM, Ted Harding
>> <Ted.Harding at manchester.ac.uk>wrote:
>>>
>>> There is at least one context where the distinction must be
>>> preserved. Example:
>>>
>>>  pnorm(1.5)
>>>  # [1] 0.9331928
>>>  pnorm(x=1.5)
>>>  # Error in pnorm(x = 1.5) : unused argument(s) (x = 1.5)
>>>  pnorm(x<-1.5)
>>>  # [1] 0.9331928
>>>  x
>>>  # [1] 1.5
>>>
>>> Ted.
>>>
>> I would regard modifying a variable within the parameters of a
>> function call as pretty tasteless. What does:
>>
>>  foo(x<-2,x)
>> or
>>  foo(x,x<-3)
>>
>> do that couldn't be done clearer with two lines of code?
>>
>>  Remember: 'eschew obfuscation'.
>>
>> Barry
>
> Tasteless or not, the language allows it to be done; and therefore
> discussion of distinctions between ways of doing it is relevant to
> Erin's question!
>
> While I am at it, in addition to the above example, we can have
>
>  x <- 1.234
>  sqrt(x=4)
>  # [1] 2
>  x
>  # [1] 1.234
>
> compared with (as in the first example):
>
>  x <- 1.234
>  sqrt(x<-4)
>  # [1] 2
>  x
>  # [1] 4
>
> There is a passage in ?"<-" (which I don't completely understand)
> which is also relevant to Erin's query about '=' vs '<-':
>
>  The operators '<-' and '=' assign into the environment in
>  which they are evaluated.  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.
>
> (I'm not too clear about the scope of "one of the subexpressions
> in a braced list of expressions").

For example:

> x = xyplot(1~1)
> system.time(x = xyplot(1~1))
Error in system.time(x = xyplot(1 ~ 1)) :
  unused argument(s) (x = xyplot(1 ~ 1))
> system.time({ x = xyplot(1~1) })
   user  system elapsed
  0.008   0.000   0.005

Of course, <- would not have had a problem. This is the most common
problem I personally have had using = for assignment (better
readability of <- is also a huge plus).

-Deepayan



More information about the R-help mailing list