env <- new.env()
d <- 1
fn <- function(a, b) {
a + b + d
}
fn2 <- (function() {
d <- 2
function(a, b) {
a + b + d
}
})()
environment(fn2)
# function: (formal_parameters, body, environment)
function(a, b) { c; d }
`function`(alist(a=, b=), quote({ c; d }), GlobalEnv())
formals(fn)
body(fn)
environment(fn)
environment(fn2)$d <- 3
fn2(1, 2)
# fn2 gets it values from environment(fn2)
# if d is present in environment(fn2), it gets taken from there
# otherwise, we traverse the "parent environment chain"
rm("d", envir = environment(fn2))
fn4 <- function(a, d) {
a + d
}
fn3 <- local({
local({
d <- 5
local({
d <- 1
local({
function(a, b) {
a + b + d
}
})
})
})
})
search() # gives you the package search path
# Within packages, local variables and functions are
# found from:
# function environment, package namespace, imports namespace,
# copy of base, global env
env <- new.env()
env$d <- 8
makeActiveBinding("d", function() env$d, env = environment(fn3))
F <- function(a, b) {
browser()
a + b
}
G <- local({
d <- 5
function() {
F(1, 2)
}
})
H <- local({
G()
})
Z <-
(function(){
print("1")
print(environment())
(function(){
print("2")
print(environment())
(function(){
print("3")
print(environment())
print(parent.env(environment()))
print(parent.env(parent.env(environment())))
print(parent.frame())
print(parent.frame(2))
print(parent.frame(3))
print(parent.frame(4))
print(parent.frame(5))
stop("error")
})()
})()
})()
big_fn <- local({ function(a, b) {
a + b
} })
Last active
July 31, 2017 20:02
-
-
Save robertzk/1b623aebd4c63ca50f565737dad5bfe9 to your computer and use it in GitHub Desktop.
Lunch & Learn 07/30/17: R environments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment