Joezerz
Joezerz

Reputation: 151

How to use R environments inside package?

I'm having a problem where a variable seems to not be found using with()

I have a package, with internal data that is an environment (ENV); so every function within my package can access (and modify) ENV.

Essentially I'm using the following code inside my package:

In /data-raw I make an environment, and save it to /data

ENV = new.env()
ENV$A = 2
ENV$B = 3

And in my package:

foo<-function(bar){
  with(ENV,{
    if(nrow(bar)==0){
      print(ENV$A)
    } else {
      print(ENV$B)
    }
  })
}

bar = data.frame()
foo(bar)

What I actually get is: Error in nrow(bar) { : object '.result' not found

I thought the function environment would be the parent of the with environment... Can I not access the function's variables like this?

Thanks for any help.

Update

So, they're definitely in different places. The parent environment inside the function is my package namespace, whereas the parent inside with is the global environment.

Upvotes: 1

Views: 676

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546153

I thought the function environment would be the parent of the with environment...

No: the parent environment of with is the parent environment of the environment. In fact, that’s one of the fundamental issues that commands such with have.

To work around this you could convert your environment to a list (via as.list). Of course that copies all objects in the environment so it’s potentially inefficient. It also makes modifying objects inside the environment impossible.

Upvotes: 1

Related Questions