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?