首页 > 解决方案 > 在不同的环境中调用时,部分粘合函数不起作用

问题描述

我已经在我正在处理的项目中对功能进行了局部化,这样我们就可以使用商定的分隔符,而不必一直告诉胶水它们。但是当我们在另一个函数中使用偏函数时,它停止工作:glue

library(purrr)
library(glue)

glue_query <- partial(glue, .open = "<<", .close = ">>")

# case 1: use partialised function in same scope
x <- 15
glue_query("There are <<x>> apples here!")
#> There are 15 apples here!

# case 2: use partialised function in different scope
myfunc_partialised <- function(y) {
  glue_query("The thing I called y is actually <<y>>")
}
myfunc_partialised(15)
#> Error in eval(parse(text = text, keep.source = FALSE), envir): object 'y' not found

# case 3: use function directly
myfunc_regular <- function(z) {
  glue("The thing I called z is actually <<z>>", .open = "<<", .close = ">>")
}
myfunc_regular(15)
#> The thing I called z is actually 15

reprex 包于 2021-07-09 创建 (v2.0.0 )

我的感觉是在它定义glue_query的环境中寻找要插入的对象,而不是在它被调用的环境中。这就是这里发生的事情吗?我可以指示它使用调用环境吗?我想在我的整个包裹中使用它!

编辑:我知道glue有一个.envir参数可以控制表达式在哪个环境中进行评估,但我不太确定使用什么来确保它在这里玩得很好!

标签: rpurrrr-environmentr-glue

解决方案


这似乎确实partial()使获得正确的环境变得更加困难。相反,您可以编写自己的包装器

glue_query <- function(..., .open = "<<", .close = ">>", .envir=parent.frame()) {
  glue(..., .open=.open, .close=.close, .envir=.envir)
}

这将适用于您提供的两个测试用例。


推荐阅读