[R] advice/opinion on "<-" vs "=" in teaching R
Duncan Murdoch
murdoch at stats.uwo.ca
Fri Jan 15 13:22:21 CET 2010
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?
>
The most common use I see that I like is within a conditional test like
if ( !is.null(x <- get("x", somehow)) && length(x) == 1) { dosomething }
The x variable is only used for the test, but since it is used twice
there, the assignment saves getting it twice. You could expand it to
two lines
x <- get("x", somehow)
if ( !is.null(x) && length(x) == 1) { dosomething }
but I find that a tiny bit harder to read.
On the other hand, I would never use the examples you gave, because I'd
have no idea what the value of x would be, since it depends on the order
of evaluation of the arguments. In R, I don't even know for sure if the
assignment would be evaluated at all, let alone before the x argument.
Duncan Murdoch
> Remember: 'eschew obfuscation'.
>
> Barry
>
>
More information about the R-help
mailing list