您如何处理包内部的R Data? [英] How do you handle R Data internal to a package?

查看:91
本文介绍了您如何处理包内部的R Data?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的R包需要几个R数据对象,例如预先计算的模型和参数.

The R package I am developing requires several R data objects, such as pre-computed models and parameters.

当前,我在单个.RData文件的包的数据"目录中拥有每个对象.使用软件包时,用户可以使用数据"功能将这些对象附加到他们的环境中.

Currently I have each object in the 'data' directory of the package in individual .RData files. When using the package users can use the "data" function to attach these objects to their environment.

我想要的行为是,在加载程序包时,数据对象会自动附加到内部程序包环境中,并且用户无法直接访问.

The behaviour I would like instead would be that on loading the package the data objects are automatically attached to the internal package environment and not accessible to the user directly.

我的理解是,将"sysdata.rda"文件放在包含数据"中当前对象的程序包的"R"目录中,将为我提供所需的结果.但是,有没有一种方法可以使每个对象放在单独的文件中而不是分组在一起?

My understanding is that placing a 'sysdata.rda' file in the 'R' directory of the package containing the objects currently in 'data' will give me the desired result. However, is there a way to do this so that I can have each object in a separate file instead of grouped together?

推荐答案

加载包时,可以使用.onLoad()钩子调用data(),并将包名称空间指定为加载数据的环境.对象进入.

You can use the .onLoad() hook to call data() when your package is being loaded, and specify the package namespace as the environment where to load the data objects into.

假设在名为foopkg的程序包的data/目录中有文件model1.Rmydata.RData,请定义函数

Assuming you have files model1.R and mydata.RData in the data/ directory of your package called foopkg, define the function

.onLoad <- function(libname, pkgname) {
  data("model1", "mydata", package=pkgname, envir=parent.env(environment()))
}

包裹中的某个位置(例如,在foopkg-package.R中).

somewhere in your package (e.g. in foopkg-package.R).

构建并安装软件包后,

> library(foopkg)
> ls(loadNamespace("foopkg")) 

应该证明各种数据对象已成功加载到程序包名称空间中,即对程序包中的函数可见,但不会污染全局环境.

should demonstrate that the various data objects were successfully loaded into the package namespace, i.e. visible to functions in your package but not polluting the global environment.

这篇关于您如何处理包内部的R Data?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆