[R-pkg-devel] mget with Inherits Not Finding Variable in Caller

Simon Urbanek @|mon@urb@nek @end|ng |rom R-project@org
Wed Dec 1 00:25:19 CET 2021


Dario,


> On Dec 1, 2021, at 12:00 PM, Dario Strbenac <dstr7320 using uni.sydney.edu.au> wrote:
> 
> Good day,
> 
> What I am misunderstanding about the inherits = TRUE option of mget? I expect the small example to work.
> 
> f <- function(x, .iteration = i) g() 
> g <- function() mget(".iteration", inherits = TRUE)
> f(10, 1)
> Error: value for ‘.iteration’ not found
> 

That has nothing to do with inherits and is expected - it's identical to

> f <- function(x, .iteration = i) g() 
> g <- function() .iteration
> f(10, 1)
Error in g() : object '.iteration' not found

Please note that R is lexically scoped and you defined g in the global environment so it has no way of seeing inside f. This would work:

> f <- function(x, .iteration = i) {
+   g <- function() .iteration
+   g() 
+ }
> f(10, 1)
[1] 1

since then the environment of f is the parent env of g.

If you want dynamic scoping (not what R uses!) you can use dynGet():

> f <- function(x, .iteration = i) g() 
> g <- function() dynGet(".iteration")
> f(10,1)
[1] 1

but since that is non-standard the docs warn:

     ‘dynGet()’ is somewhat experimental and to be used _inside_
     another function.  It looks for an object in the callers, i.e.,
     the ‘sys.frame()’s of the function.  Use with caution.

Cheers,
Simon




> --------------------------------------
> Dario Strbenac
> University of Sydney
> Camperdown NSW 2050
> Australia
> ______________________________________________
> R-package-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-package-devel
> 



More information about the R-package-devel mailing list