简体   繁体   English

在 R 中使用 deparse 进行强制评估

[英]Force evaluation with deparse in R

I have a function that produces a function:我有一个产生函数的函数:

fun1 <- function (x)
    return (function() x)

By the time a function is produced, the value of x is already basically a constant:到函数生成时, x的值已经基本上是一个常数:

fun2 <- fun1 ("a")

However, when I have fun2 printed, it won't show the actual value, it only shows "x" even though it is by now obsolete:但是,当我打印fun2 ,它不会显示实际值,它只显示"x"即使它现在已经过时了:

> fun2
function() x
<environment: 0x55a9f94f9fc8>

How can I force the evaluation of x so that fun2 gets printed as如何强制对x进行评估,以便fun2打印为

function() "a"

or however it was produced?或者它是如何生产的?

There's no need to resort to deparse here.没有必要在这里诉诸deparse You can write the evaluated value of x into the body of the newly created function:您可以将 x 的评估值写入新创建的函数体:

fun1 <- function (x){
  f <- function() x
  body(f) <- x
  f
}

So that:以便:

fun1("a")
#> function () 
#> "a"
#> <environment: 0x00000146d0449dd8>

and

f <- fun1("a")
f()
#> [1] "a"

EDIT编辑

If you wanted f to take an argument you could do:如果你想让f接受一个论点,你可以这样做:

fun1 <- function (x){
  f <- function(y) y + x
  body(f)[[3]] <- x
  f
}

so that以便

fun1(3)
#> function (y) 
#> y + 3
#> <environment: 0x00000146d4b702a0>

This substitutes all instances of x in the body of fun .这将替换fun主体中的所有x实例。 In the example fun1 has one argument but it would continue to work with multiple fun1 arguments used in fun substituting them all into fun .在示例中fun1有一个参数,但它将继续使用fun使用的多个fun1参数将它们全部替换为fun We have also set the environment of fun to the environment in the caller of fun1 allowing the caller to change that by specifying envir if needed.我们还将fun的环境设置为fun1的调用者中的环境,允许调用者根据需要通过指定envir来更改该envir

fun1 <- function (x, envir = parent.frame()) {
    fun <- function() x
    body(fun) <- do.call("substitute", list(body(fun)))
    environment(fun) <- envir
    fun
}

fun2 <- fun1("a")
fun2
## function () 
## "a"

environment(fun2)
## <environment: R_GlobalEnv>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM