[Rd] SOLVED: search for variable in package in .GlobalEnv first

Rainer M Krug Rainer at krugs.de
Mon Oct 7 17:22:12 CEST 2013


Duncan Murdoch <murdoch.duncan at gmail.com> writes:

> On 07/10/2013 10:29 AM, Rainer M Krug wrote:
>> Hi
>>
>> First, sorry if I get the terminology wrong, I am still quite new to the
>> concept of using environments and workspaces.
>>
>> Say I have a statement in a package SIM like
>>
>> sim <- TYPE
>>
>> where the variable TYPE is initialized in the package to
>> e.g. "exponential" (SIM::TYPE == "exponential").
>>
>> Now, I want to give the user the option of specifying the variable TYPE,
>> but to the effect, that if the user does not define a variable TYPE in
>> the user workspace (.GobalEnv), the one in the namespace from the
>> package is used.
>>
>> In other words, I want to look first in the workspace, and then in SIM::
>> for the variable TYPE. How can do this?
>
> The rgl package does this when looking for defaults for
> graphics. Here's the code:
>
>
> getr3dDefaults <- function()
>     tryCatch(get("r3dDefaults", envir=.GlobalEnv),
>          error = function(e) r3dDefaults)
>
> This will find the variable r3dDefaults if it is in the global
> environment or in a package on the search path; if that fails, it
> returns the local one.  Since that function is defined in the package,
> it can see the local r3dDefaults variable.  You might not want to
> accept anything except what is in .GlobalEnv; in that case, use
> inherits = FALSE in the call to get().

Thanks a lot - works like a charm.

I actually like the ide of searching the searchpath down.

Thanks,

Rainer

>
> Duncan Murdoch
>
<#secure method=pgpmime mode=sign>

-- 
Rainer M. Krug

email: RMKrug<at>gmail<dot>com



More information about the R-devel mailing list