Skip to content

Instantly share code, notes, and snippets.

@JonasMoss
Created July 12, 2019 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonasMoss/59a996b933b3aaf3001fa67d4c99faba to your computer and use it in GitHub Desktop.
Save JonasMoss/59a996b933b3aaf3001fa67d4c99faba to your computer and use it in GitHub Desktop.
Define functions inside enclosing environment.
#' Hide non-function variables from function.
#'
#' @param ... Named functions and function definitions.
#' @return Nothing.
H = function(...) {
function_names = names(as.list(substitute((...)))[-1])
function_defs = list(...)
envir = parent.env(parent.frame())
for(i in 1:length(function_names)) {
environment(function_defs[[i]]) = envir
assign(x = function_names[[i]],
value = function_defs[[i]],
envir = envir)
}
}
a = 5
H(adder = function(x) x + 2 + a)
adder(0)
# Error in adder(0) : object 'a' not found
H(fun1 = function(x) x + 2,
fun2 = function(x) fun1(x) + 1)
fun2(4)
# [1] 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment