r - 在不同的环境中调用时,部分粘合函数不起作用
问题描述
我已经在我正在处理的项目中对功能进行了局部化,这样我们就可以使用商定的分隔符,而不必一直告诉胶水它们。但是当我们在另一个函数中使用偏函数时,它停止工作: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
参数可以控制表达式在哪个环境中进行评估,但我不太确定使用什么来确保它在这里玩得很好!
解决方案
这似乎确实partial()
使获得正确的环境变得更加困难。相反,您可以编写自己的包装器
glue_query <- function(..., .open = "<<", .close = ">>", .envir=parent.frame()) {
glue(..., .open=.open, .close=.close, .envir=.envir)
}
这将适用于您提供的两个测试用例。
推荐阅读
- python - 我不确定为什么无法使用 Python Selenium 定位此 xpath
- reactjs - React 前端中未定义的环境变量
- d3.js - 条形图的条形之间的d3js网格线
- java - 为什么这个java代码比cpp占用更少的空间和时间
- javascript - 使用 Fetch 提交多个 formData 对象
- reactjs - 如何使用样式组件使按钮居中?
- python - 根据熊猫中的计数从数据框中排除组
- reactjs - 使用 Enzyme 和 React 时输入未通过模拟更改更新
- python - 如何修复 Google Cloud ssh“模块‘时间’没有属性‘时钟’”?
- android - “无法加载资产:null”在我的颤振应用程序中