在哪里创建包环境变量?

时间:2022-10-28 23:05:49

I'm doing a data analysis and created a package to store my vignettes and data, as explained here.

我正在进行数据分析,并创建了一个包来存储我的简介和数据,如这里所述。

I want to set some variables that would be available to all my package functions.

我想设置一些变量,这些变量对于所有的包函数都是可用的。

These variables define: the path to data sets, the measurements characteristics (such as probes positions), physical constants and so on.

这些变量定义:数据集的路径、测量特性(如探针位置)、物理常数等等。

I have read that one recommended way to store such variables is to use environments.

我读过一篇文章,建议使用环境来存储这些变量。

The question is, where do I put the script that creates the environment?

问题是,我把创建环境的脚本放在哪里?

I thought about putting it in the onLoad method, to be sure it's executed when the package is loaded.

我考虑将它放入onLoad方法,以确保在装载包时执行它。

1 个解决方案

#1


3  

If you put it in the .onLoad function (not method), you'll have to use the assign function to ensure the environment gets created in your package namespace.

如果将其放入. onload函数(而不是方法)中,则必须使用assign函数来确保在包命名空间中创建环境。

.onLoad <- function(libname, pkgname)
{
    # ...
    assign("myPackageEnvironment", new.env(), parent.env())
    # ...
}

But you can also just put it in open code:

但是你也可以把它放在开放代码中:

myPackageEnvironment <- new.env()

Informally, you can think of your package's .R files as being sourced one after another into the environment of your package namespace. So any statements that run in open code will create objects there directly.

非正式地,您可以将包的. r文件看作是一个接一个地提交到包命名空间的环境中。所以任何在开放代码中运行的语句都会直接在那里创建对象。

#1


3  

If you put it in the .onLoad function (not method), you'll have to use the assign function to ensure the environment gets created in your package namespace.

如果将其放入. onload函数(而不是方法)中,则必须使用assign函数来确保在包命名空间中创建环境。

.onLoad <- function(libname, pkgname)
{
    # ...
    assign("myPackageEnvironment", new.env(), parent.env())
    # ...
}

But you can also just put it in open code:

但是你也可以把它放在开放代码中:

myPackageEnvironment <- new.env()

Informally, you can think of your package's .R files as being sourced one after another into the environment of your package namespace. So any statements that run in open code will create objects there directly.

非正式地,您可以将包的. r文件看作是一个接一个地提交到包命名空间的环境中。所以任何在开放代码中运行的语句都会直接在那里创建对象。