crate_env {miesmuschel} | R Documentation |
Set a Function's Environment
Description
Useful to represent functions efficiently within repr()
.
Usage
crate_env(fun, namespace = "R_GlobalEnv", ..., selfref = NULL)
Arguments
fun |
( |
namespace |
( |
... |
( |
selfref |
( |
Value
function
: The given fun
with changed environment.
Examples
identity2 = crate_env(function(x) x, "base")
identical(identity, identity2) # TRUE
y = 1
f1 = mlr3misc::crate(function(x) x + y, y, .parent = .GlobalEnv)
f2 = crate_env(function(x) x + y, "R_GlobalEnv", list(y = 1))
# Note identical() does not apply because both contain (equal, but not
# identical) 'y = 1'-environments
all.equal(f1, f2) # TRUE
f1(10) # 10 + 1 == 11
factorial1 = mlr3misc::crate(
function(x) if (x > 0) x * factorial1(x - 1) else 1,
y, .parent = .GlobalEnv
)
environment(factorial1)$factorial1 = factorial1
factorial2 = crate_env(
function(x) if (x > 0) x * factorial1(x - 1) else 1,
"R_GlobalEnv", list(y = 1), selfref = "factorial1")
# putting 'factorial1' into the list (or repeating function(x) ....)
# would *not* work, since we want:
identical(environment(factorial2)$factorial1, factorial2) # TRUE
all.equal(factorial1, factorial2) # TRUE
g = crate_env(function(x) x + y + z, "miesmuschel",
list(y = 1), list(z = 2), selfref = c(X = 1, Y = 2, Z = 2))
g(0) # 0 + 1 + 2 == 3
identical(environment(g)$X, g)
identical(parent.env(environment(g))$Y, g)
identical(parent.env(environment(g))$Z, g)
identical(
parent.env(parent.env(environment(g))),
loadNamespace("miesmuschel")
)