execute_in: Execute a function in an environment

View source: R/all.R

execute_inR Documentation

Execute a function in an environment

Description

Run a function in an environment other than Global. One way to use this is to take other people's code that uses global objects and create wrapper functions where those objects can be passed in.

Usage

execute_in(f, env, ...)

Arguments

f

the function

env

the environment you want to run in

...

parameters to the function

Value

Returns whatever f is supposed to return.

Examples

# A function I get from a colleagues code
# Imagine it is something you cannot re-write easily
bad_func <- function(n) {
  set.seed(0)
  return(rnorm(n, mean = mu, sd = mu / 2))
}

mu <- 5
bad_func(3)

good_func <- function(n, mu) {
  temp_env <- new.env()
  temp_env$mu <- mu
  execute_in(bad_func, temp_env, n = n)
}

good_func(3, 5)
good_func(3, 10)


adamleerich/alrtools documentation built on March 12, 2024, 11:38 p.m.