[R] Is there any difference between <- and =

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Mar 13 11:33:20 CET 2009


Sean Zhang wrote:
> Dear Jens and Wacek:
>
> I appreciate your answers very much.
>
> I came up an example based on your comments.
> I feel the example helped me to understand...(I could be missing your points
> though :( )
> If so, please let me know.
> Simon pointed out the following link:
> http://www.stat.auckland.ac.nz/mail/archive/r-downunder/2008-October/000300.html
> I am still trying to understand it...
> My question is how my conclusion (see at the end of the example below) drawn
> from "lexical scope" perspective is related to
> an understanding from an "environment" perspective (if an understanding from
> "environment" perspective validly exists).
>
> Thank you all again very much!
>
> -Sean Zhang
>
> #My little example is listed below
> f1<-function(a=1,b=2) {print(a); print(b); print(a-b) }
> f1()  #get 3, makes sense
>   

-1?

> f1(2,) #get 0, makes sense
> a <- 10
> b <- 20
> f1(a=a+1,b=a)
> a  #get 10  a is not changed outside function scope
> b  #get 20, b is not changed outside function scope
> a <- 10
> b <- 20
> f1(a <- a+1, b <- a)
>   

this is what you *really* shouldn't do unless you know what you're
doing.  here you have not only the issue of whether the assignment will
actually be made, but also the issue of the order of evaluation of the
argument expressions, which depends on the when the arguments are used
within the function.

    f = function(a, b, c)
       if (c) a-b
       else b-a

    a=1; b=1; f(a <- a+1, b <- a, TRUE)
    # 0
    a
    # 2
    b
    # 2
   
    a=1; b=1; f(a <- a+1, b <- a, FALSE)
    # -1
    a
    # 2
    b
    # 1



> a   #a is now 11, a is changed outside function
> b   #b is now 11  b is changed outside function
> a <- 10
> b <- 20
> f1({a=a+1},{b = a})
> a #a is changed into 11
> b #b is changed into a(i.e., 11)
>
> a <- 10
> b <- 20
> f1((a=a+1),(b = a))
> a #a is changed into 11
> b #b is changed into a(i.e., 11)
> #my conclusion based on testing the example above is below
> #say argument is a, when used inside paraenthesis of
> whatever.fun<-function()
> #a<-something, (a=something) , and {a<-something}
> #are the same. They all change the values outside the function's scope.
> #Typically, this breaks the desired lexical scope convention. so it is
> dangerous.
>   

i don't think you break lexical scoping here. 

vQ




More information about the R-help mailing list