[R] Scope

Roger Bivand Roger.Bivand at nhh.no
Thu Feb 8 22:52:06 CET 2007


On Thu, 8 Feb 2007, Gabor Grothendieck wrote:

> You can assign the environment within main to a variable in
> the global environment and that will make it accessible even
> after main terminates:

Indeed, it can be done, but unless the original questioner is already 
expert at handling scopes and environments, this is an easy way to get 
muddled. Functions take arguments and return values, so putting the output 
into a suitable object and assigning that object:

cars_lm <- lm(dist ~ speed, data=cars)

is robust, easy to grasp, and in particular easy to debug. Thinking
through the design of the output object is usually helpful. Assigning to
the global environment will overwrite objects unless one is careful, and
even with years of experience only seems worth considering when no
feasible alternative exists; on consideration, alternatives usually
appear.

> 
> main <- function() {
>  assign("main.env", environment(), .GlobalEnv)
>  x <- 1; y <- 2
> }
> 
> main()
> main.env$x
> main.env$y
> # or
> attach(main.env)
> search()  # note that main.env is on search path
> x
> y
> detach()  # remove from path now that we are finished
> 
> 
> Alternately you could assign each variable within main
> that you want to save:
> 
> main <- function() {
>  x <- 1; y <- 2
>  assign("x", x, .GlobalEnv)
>  assign("y", y, .GlobalEnv)
> }
> 
> main()
> x
> y
> 
> 
> 
> On 2/8/07, Geoffrey Zhu <gzhu at peak6.com> wrote:
> > Hi all,
> >
> > When I write a script, I'd like to create a main() function so that I
> > only need to type main() t re-run it. However, I'd like all the
> > variables in main() to be global so that when the function terminates, I
> > still have access to the variables in the environment. Does anyone know
> > how to do that?
> >
> > Best regards,
> > Geoffrey
> >
> >
> >
> > _______________________________________________________=0A=
> > =0A=
> > =0A=
> > The information in this email or in any file attached hereto...{{dropped}}
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch 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.
> >
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
> 

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-help mailing list