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:<jdnew...@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.p...@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
>>

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to