10

My latest submission to CRAN got bounced back because I have assignments to the global environment which is now frowned upon.

I have an embedded data set (sysdata.rda) that contains configuration parameters based upon state (as in United States) the user resides. I have wanted this embedded data set to be updatable when a new user uses the program. I previously updated this data in the initial function the user uses and made it accessible to the user via global assignment.

I am struggling to figure out how to update this embedded data and make it the default data that the user uses for the remainder of their session.

Previously I housed the data in /data and recently switched it to /R/sysdata.rda as it seemed more suited for that locale. Now I'm not so sure.

Any help greatly appreciated

4

2 回答 2

4

关键是在全局环境之外的环境中进行分配。有两种基本技术,使用local()<<-/或显式创建新环境:

使用显式环境很简单:创建环境,然后像列表一样分配给它:

my_opts <- new.env(parent = emptyenv())
set_state <- function(value) my_opts$state <- value
get_state <- function() my_opts$state

使用local()有点复杂,需要一些技巧<<-

set_state <- NULL
get_state <- NULL

local({
  state <- NULL
  get_state <<- function() state
  set_state <<- function(value) state <<- value
})

有关如何<<-工作的更多信息,请参阅https://github.com/hadley/devtools/wiki/environments,在“分配:将名称绑定到值”部分。

于 2013-01-13T20:21:09.250 回答
1

为什么没有一个foo.R文件/data来加载数据并在用户调用时对其进行更新data(foo)?这是允许的选项之一/data,但请注意编写 R 扩展中的以下内容

请注意,R 代码应该是“自给自足的”,而不是使用包提供的额外功能,这样数据文件也可以在无需加载包的情况下使用。

如果您可以忍受该限制,则data(foo)可以加载数据,更新它,并确保它位于特定的命名对象中,然后您可以在函数中引用该对象。

于 2013-01-13T11:42:58.690 回答