将参数传递给使用替换的函数
我想创建一个小的 reprex 包装器,将输入代码传递给 reprex::reprex()
。 由于 reprex 在其 x 参数上使用 substitute()
,我需要以某种方式转义它。
MWE
一个最小的工作示例是这样的,其中 internal_foo()
充当 reprex()
的代理。 预期结果是对 internal_foo(...)
的调用以及对 wrapper(...)
的调用都返回相同的输出。
internal_foo <- function(x) {
res <- substitute(x)
res
}
# the expected output! ------
internal_foo({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
#> {
#> a <- 1:10
#> b <- rnorm(10)
#> plot(a, b)
#> }
wrapper <- function(x = NULL) {
# pass x to internal_foo in such a way that it has the same output as calling internal_foo directly
internal_foo(deparse(x))
}
wrapper({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
#> deparse(x)
# clearly not equal to the expected output ----
由于 Rs 惰性求值,x
并未按照我的预期方式传递给 internal_foo()
。
我尝试过 eval、deparse 和替代,但我找不到正确的组合。
更复杂的 reprex 示例
实际目标是这个 reprex 包装器。
wrapper2 <- function(x, input = NULL) {
reprex::reprex(x = x, input = input, venue = "r", html_preview = FALSE)
}
wrapper2({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
wrapper2
渲染 reprex 并将其复制到剪贴板,但显示未找到 eval 对象 x 错误
。
I want to create a small wrapper to reprex that passes input code to reprex::reprex()
.
As reprex uses substitute()
on its x argument, I need to somehow escape it.
MWE
A minimal working example is this, where internal_foo()
acts as a surrogate for reprex()
.
The expected result is that both the call to internal_foo(...)
as well as to the wrapper(...)
return the identical output.
internal_foo <- function(x) {
res <- substitute(x)
res
}
# the expected output! ------
internal_foo({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
#> {
#> a <- 1:10
#> b <- rnorm(10)
#> plot(a, b)
#> }
wrapper <- function(x = NULL) {
# pass x to internal_foo in such a way that it has the same output as calling internal_foo directly
internal_foo(deparse(x))
}
wrapper({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
#> deparse(x)
# clearly not equal to the expected output ----
Due to Rs lazy evaluation, x
is not handed trough to internal_foo()
the way I intend it to.
I have played around with eval, deparse, and substitute but I cannot find the right combination.
The more complicated reprex example
The actual target is this reprex wrapper.
wrapper2 <- function(x, input = NULL) {
reprex::reprex(x = x, input = input, venue = "r", html_preview = FALSE)
}
wrapper2({
a <- 1:10
b <- rnorm(10)
plot(a, b)
})
wrapper2
renders the reprex and copies it to clipboard but shows Error in eval object x not found
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以做
哪些输出:
You could do
Which outputs: