0

I need to call a function, named g, whose behavior depends on the variable under globalenv() several times. For convenience, I try to wrap it into a helper function, named f. However, I hope that after executing f, the globalenv() is invariant.

Here is my implementation so far:

g <- function(name) {
  print(globalenv()[[name]])
}

f <- function(w) {
  # backup "w" in globalenv if needed
  is_existed.w <- !is.null(globalenv()[["w"]])
  if (is_existed.w) {
    temp.w <- globalenv()[["w"]]
  }
  w <<- w
  g("w")
  # restore w if needed
  if (is_existed.w) {
    w <<- temp.w
  }
}

w <- "a"
f("gg")
w

However, this approach is very tedious. I need to copy-paste many times. Is there an more elegant way to implement this?

4

1 回答 1

2

为什么需要复制和粘贴?如果是因为你想保存不同的变量,或者调用不同的函数,你可以将这两个作为参数传递给更高阶的函数,即返回函数的函数,如下所示:

wrap <- function(name, g) {
  f <- function(value, ...) {
    old <- globalenv()[[name]]
    assign(name, value, globalenv())
    res <- g(...)
    if (!is.null(old))
      assign(name, old, globalenv())
    return (res)
  }
  return (f)
}

然后您可以创建您的fusingwrap("w", g)并调用它 using f("gg", "w"),后者"w"是您要打印的变量的名称。

于 2013-07-16T05:49:21.417 回答