Eval inside gsubfn inside subfunction: object not found

Give two functions

subfun <- function(txt) 
  gsubfn::gsubfn("§([^§]+)§", ~eval(parse(text=x)), txt)

topfun <- function(id = 1L) 
  subfun("Hello §id§ world!")

The following (1.) should give "Hello 1 world!", but instead produces an error:

topfun() 
# Error in eval(expr, envir, enclos) : object 'id' not found

These two (2.) and (3.) work as expected:

id <- 2L
topfun()
# [1] "Hello 2 world!"

topfun2 <- function(id = 1L) 
  gsubfn::gsubfn("§([^§]+)§", ~eval(parse(text=x)), "Hello §id§ world!")
topfun2() 
# [1] "Hello 1 world!"

How can I do the job (1.)?

I tried a few options environment()and parent.frame()a parameter envir evaland gsubfnincluding the transmission topfunmedium on subfunusing the ellipsis argument. All without success. (Not that I knew more about what was going on under the hood. But I would expect R to go into one parent environment after another to search id...)

I use R version 3.3.0and gsubfnversion of the package 0.6.6.

Thanks in advance!

+4
1

, replacement gsubfun. , eval, .

subfun_2 <- function(txt){
  ev <- parent.frame() # the environment in which subfun_2 was called
  gsubfn::gsubfn("§([^§]+)§", ~eval(parse(text=x), envir = ev), txt)
}
topfun_2 <- function(id = 1L) subfun_2("Hello §id§ world!")
topfun_2()
# Error in eval(parse(text = x), envir = ev) : 
#  argument "ev" is missing, with no default

, :

subfun_3 <- function(txt){
   ev <- parent.frame() 
   gsubfn::gsubfn("§([^§]+)§", function(x)eval(parse(text=x), envir = ev), txt)
}
topfun_3 <- function(id = 1L) subfun_3("Hello §id§ world!")
topfun_3()
# Hello 1 world!
+2

Source: https://habr.com/ru/post/1648698/


All Articles