[R] Issue with special assignment operator

AROONALOK PYNE aroonalok.pyne at gmail.com
Mon Mar 17 08:11:09 CET 2014


Thanks a lot Jeff for the reply. I usually do what you said i.e,
return a value from the function and save it in the calling
environment when I call the function, but I just wanted to experiment
with the special assignment operator. Could you clarify a small doubt
of mine :

I agree that x refers to the local version inside foo(). But, once I
do x <<- 8 inside foo() (as done in the code), isn't the local version
of x supposed to change too?

On 3/17/14, Jeff Newmiller <jdnewmil at dcn.davis.ca.us> wrote:
> Because x refers to the local version, not the global one.
>
> In case you have not read this before, using <<- is a really really bad
> idea. Your code will become confusing and likely be wrong if you ignore this
> warning. Return a value from the function and save it in the calling
> environment when you call the function.
> ---------------------------------------------------------------------------
> Jeff Newmiller                        The     .....       .....  Go Live...
> DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
>                                       Live:   OO#.. Dead: OO#..  Playing
> Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
> /Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
> ---------------------------------------------------------------------------
>
> Sent from my phone. Please excuse my brevity.
>
> On March 16, 2014 9:06:13 PM PDT, AROONALOK PYNE <aroonalok.pyne at gmail.com>
> wrote:
>>Hi
>>
>>Please explain why the function 'foo()' is not printing x as 8 in the
>>following code :
>>
>>> foo <- function(){
>>+ x <- 10
>>+ if(x){
>>+ x <<- 8
>>+ }
>>+ print(x)
>>+ }
>>> foo()
>>[1] 10
>>> x
>>[1] 8
>>>
>
>


-- 
*AROONALOK PYNE*

BE Graduate
Department Of Computer Science And Engineering
Jadavpur University, Kolkata-32
India




More information about the R-help mailing list