Apostolos Polymeros
Apostolos Polymeros

Reputation: 843

R's environment

I would like to ask something about R's environments: In the next simple code I create the local variable "v1". "f1" lays in the global environment, as we can see when we type "environment(f1)". My question is how can we access "v1" from within the R console. "v1$f1" is not working. Is there an explanation for this?

rm(list = ls())
f1 <- function() {
    v1 <- 1
}
environment(f1)

Next, if I create the environment "e1"

e1 <- new.env()

and I put "f1" inside "e1"

environment(f1) <- e1

When I use "ls(e1)" I do not receive "f1". Does anybody know why?

ls(e1)

Thank you in advance

Upvotes: 2

Views: 708

Answers (1)

Tommy
Tommy

Reputation: 40871

The local variable v1 does not exists until you call the function f1, and then the environment where it lives is typically destroyed when f1 exits. But you can get hold of it if you modify f1:

rm(list = ls())
f1 <- function() {
    v1 <- 1
    environment() # return the local environment
}

f1()$v1

For your second question, you assigned e1 to f1, not the other way around. So f1 has the environment e1 where it looks for things. If you specify a parent environment to new.env, that's where it will continue looking for stuff:

e1 <- new.env(parent=baseenv())
e1$foo <- 42
bar <- 43 # Global variable, not found through e1

f2 <- function() {
   foo # Finds in e1
   bar # Not found...
}

environment(f2) <- e1
f2() # Error: object 'bar' not found
ls(e1) # "foo"
e1$f2 <- f2
ls(e1) # "f2" "foo"

Upvotes: 4

Related Questions