R variables created inside chunks - global space?

2,685 views
Skip to first unread message

el231bat

unread,
May 11, 2012, 12:21:02 PM5/11/12
to kn...@googlegroups.com
Quick question - how come R variables created in a chunk are put into the global space i.e. they're not like R functions where variables have function-scope. 

i.e. 

<<setup-code echo=FALSE>>=
 fooVar = seq(1:10)
@

Is there way to enable/disable this behavior or am I doing something wrong? 

Thanks

Yihui Xie

unread,
May 11, 2012, 1:43:27 PM5/11/12
to el231bat, kn...@googlegroups.com
Variables are created in the global environment so that they are
accessible to all chunks. For cached chunks, they are created in an
empty environment first and copied to globalenv() later so that knitr
knows which variables are newly created and can cache them
accordingly.

Currently there is no way to disable knitr using globalenv(). What is
your concern on this?

Regards,
Yihui
--
Yihui Xie <xiey...@gmail.com>
Phone: 515-294-2465 Web: http://yihui.name
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA

el231bat

unread,
May 11, 2012, 2:03:22 PM5/11/12
to kn...@googlegroups.com, el231bat
The immediate concern is that if I run the report with different parameters (which controls which data-set to obtain and consider), then if there is a problem with obtaining the data or otherwise, the report will still execute and utilize the last known values for those variables to compute statistics/plot graphs. There are probably ways around it like in my setup code, always re-initializing the required variables or trying to analyse the result of fetching the data-set and exiting or raising or a error. I would've imagine that it's fine to have variables exist in the scope of the knit-function (so that chunks can utilize variables) but they are cleared for the next run. Wouldn't that make sense for "cache=FALSE"?  

Perhaps there is better workflow that I'm missing. I did see people suggesting using brew + knitr so that I won't have to define the input parameters in the global env. 

Thanks   

Yihui Xie

unread,
May 11, 2012, 3:02:10 PM5/11/12
to el231bat, kn...@googlegroups.com
OK, this make sense. I think I will add an argument to knit() so that
the code can be evaluated in a separate environment
(https://github.com/yihui/knitr/issues/228).

For now, you may explicitly remove the variables before creating them,
e.g. if (exists('foo')) rm(list = 'foo')

Regards,
Yihui
--
Yihui Xie <xiey...@gmail.com>
Phone: 515-294-2465 Web: http://yihui.name
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA


Reply all
Reply to author
Forward
0 new messages