functional programming - R errors indirect calling of argument -
this 1 of examples when '['
error occurs :
> libs=.packages(true) > library(help=libs[1]) błąd w poleceniu 'find.package(pkgname, lib.loc, verbose = verbose)': nie ma pakietu o nazwie ‘[’
r
behaves differently when use argument directly library(help="base")
versus indirect use : x="base"; library(help=x)
, why r
thinks ask x
packages, mechanism used ? think solution somewhere here : http://adv-r.had.co.nz/
looking @ source of library
, find following code
if (!character.only) <- as.character(substitute(help))
the substitute
says that
substitute returns parse tree (unevaluated) expression expr, substituting variables bound in env
where env
means current evaluation environment. libs
bound in .globalenv
, not in environment of function library
.
a simple example of doing
x="a" test_fun=function(x) { as.character(substitute(x)) } test_fun(x) #"x"
however, if x
defined within function body
#delete previous definition of x, if necessary #rm(list="x") test_fun=function(x) { x="a" as.character(substitute(x)) } test_fun(x) #"a"
one interesting aspect can read further down of substitute
substitution takes place examining each component of parse tree follows: if not bound symbol in env, unchanged. if promise object, i.e., formal argument function or explicitly created using delayedassign(), expression slot of promise replaces symbol. if ordinary variable, value substituted, unless env .globalenv in case symbol left unchanged.
the last part "unless env .globalenv in case symbol left unchanged" interesting because
x="a" as.character(substitute(x)) "x"
this because env
.globalenv
in case. then, substitution not take place. sure there reason - still surprising me.
Comments
Post a Comment