Skip to content

Puzzled by eval

2 messages · Duncan Murdoch, Gabor Grothendieck

#
On 06/11/2015 8:20 AM, Therneau, Terry M., Ph.D. wrote:
I think the best description is Luke's article on namespaces, "Name 
space management for R". Luke Tierney, R News, 3(1):2-6, June 2003. 
There's a link to it from the "Technical papers" section of the HTML 
help index.  There's also a short description of this in the R Language 
Definition manual in the "Search path" section 3.5.4.
If that code is in a function anywhere (package or not), cos will be a 
local variable created there in the evaluation environment created when 
you evaluate the function.  If you execute it at the command line, 
you'll create a variable called "cos" in the global environment.  Local 
variables come ahead of the 3 places I listed.  (This is why Luke's 
article is good:  it doesn't oversimplify.)

There's one other twist.  Even with cos being a local variable, 
cos(theta) would find base::cos, because the evaluator knows it is 
looking for a function (since it's a function call) and will skip over 
the local dataframe named cos.

Duncan Murdoch
#
This code which I think I wrote but might have gotten from elsewhere a
long time ago shows the environments that are searched from a given
function, in this case chart.RelativePerformance in
PerformanceAnalytics package.   Try it on some of your functions in
and out of packages to help determine the sequence of environments R
searches along:

library( PerformanceAnalytics )  ## change as needed
x <- environment(chart.RelativePerformance) ## change as needed
str(x)
while (!identical(x, emptyenv())) {
    p <- parent.env(x)
    cat("---- child is above this line and parent is below ----\n")
    str(p)
    if (isBaseNamespace(p)) cat("Same as .BaseNamespaceEnv\n")
    if (identical(p, baseenv())) cat("Same as baseenv()\n")
    if (identical(p, emptyenv())) cat("Same as emptyenv()\n")
    if (identical(p, globalenv())) cat("Same as globalenv()\n")
    x <- p
}
On Fri, Nov 6, 2015 at 9:47 AM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote: