wush978
wush978

Reputation: 3174

Replace and restore the object in `globalenv()` during a function call

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?

Upvotes: 0

Views: 68

Answers (1)

MvG
MvG

Reputation: 60868

Why do you need to copy and paste? If it is because you'd want to save different variables, or call different functions, you could pass both of these as arguments to a higher order function, i.e. a function returning a function, like this:

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)
}

You could then create your f using wrap("w", g) and call it using f("gg", "w"), the latter "w" being the name of the variable you want to print.

Upvotes: 2

Related Questions