0

我想创建一个本身使用 awesome 函数的glue::glue函数。

但是,当我想粘合一个存在于函数和全局环境中的变量时,我发现自己正在处理一些命名空间问题:

x=1

my_glue <- function(x, ...) {
    glue::glue(x, ...)
}
my_glue("foobar x={x}") #not the expected output
# foobar x=foobar x={x}

我宁愿保留以x包一致性命名的变量。

我最终做了这样的事情,到目前为止效果很好,但只是推迟了问题(很多,但仍然):

my_glue2 <- function(x, ...) {
    x___=x; rm(x)
    glue::glue(x___, ...)
}
my_glue2("foobar x={x}") #problem is gone!
# foobar x=1
my_glue2("foobar x={x___}") #very unlikely but still...
# foobar x=foobar x={x___}

有没有更好/更清洁的方法来做到这一点?

4

1 回答 1

2

由于值x = 1没有传递给函数,在当前场景中,一种方法是在将值x传递给函数之前评估全局环境本身中存在的字符串。

my_glue(glue::glue("foobar x={x}"))
#foobar x=1

my_glue(glue::glue("foobar x={x}"), " More text")
#foobar x=1 More text

另一种选择(我认为这是您正在寻找的答案)是x从父环境中获取价值。glue.envir参数,其中可以定义评估表达式的环境。

my_glue <- function(x, ...) {
   glue::glue(x, ...,.envir = parent.frame())
}
my_glue("foobar x={x}")
#foobar x=1
于 2020-03-08T11:04:52.663 回答