R Packages - Why are environments not associated with the package in which they are contained?

StackOverflow https://stackoverflow.com/questions/21533645

  •  06-10-2022
  •  | 
  •  

Question

For instance, I have an environment myEnv which lives in my package Test. So why on earth does getPackageName(myEnv) return the current time "2014-02-03 17:17:23" instead of "Test"??

# In /R/Test.R
myEnv <- new.env()
print(getPackageName(myEnv))

# Now build in RStudio:
==> Rcmd.exe INSTALL --no-multiarch --with-keep.source Test

<other messages here>

** preparing package for lazy loading
[1] "2014-02-03 17:17:23"
Warning in getPackageName(myEnv) :
  Created a package name, '2014-02-03 17:17:23', when none found

<etc etc etc>

I don't see this behaviour or its reasoning documented anywhere. Indeed, this can wreak havoc, as clearly demonstrated by this question, hence every time I create an environment I have to remember to do something like setPackageName("Test", myEnv) to associate it with my package.

This just seems superfluous and unnecessary, so why have this behaviour?

Était-ce utile?

La solution

Try getting the parent environment of your env instead of the environment itself.

This seems to work at least for a simple example I'm installing using devtools, so who knows what tricks Hadley does with environments in there:

> parent.env(myEnv)
<environment: namespace:Test>
> getPackageName(parent.env(myEnv))
[1] "Test"

This doesn't work for other objects defined in the package:

> foo
function(){
}
<environment: namespace:Test>
> getPackageName(parent.env(foo))
Error in parent.env(foo) : argument is not an environment

you just have to get the environment thus:

> getPackageName(environment(foo))
[1] "Test"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top