[R] Issue with special assignment operator

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Mon Mar 17 06:25:57 CET 2014


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
>>




More information about the R-help mailing list