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 <jdnew...@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:<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 >>> > > -- *AROONALOK PYNE* BE Graduate Department Of Computer Science And Engineering Jadavpur University, Kolkata-32 India ______________________________________________ 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.