R:如何在包中使用get和set函数?

时间:2015-06-07 06:55:37

标签: r

我正在尝试用R和RStudio,我现在卡住了。是否可以创建一个只包含在该包内的变量可见的R包?我无法在网上找到全面的例子。

这是一个小例子:

gEnv <- new.env()

a <- ""
b <- "Beta"
assign(a, "alpha", envir=gEnv)
assign(b, "beta", envir=gEnv)

getA <- function()
{
  return(get(a, envir=gEnv))
}

getB <- function()
{
  return(get(b, envir=gEnv))
}

setA <- function(x)
{
  return(assign(a, x, envir=gEnv))
}

setB <- function(x)
{
  return(assign(b, x, envir=gEnv))
}

当我尝试构建&amp; amp;重新加载&#39;,我收到以下错误:

==> Rcmd.exe INSTALL --no-multiarch --with-keep.source globalVar

* installing to library 'C:/Users/*masked*/Documents/R/win-library/3.2'
* installing *source* package 'globalVar' ...
** R
** preparing package for lazy loading
Error in assign(a, "alpha", envir = gEnv) : 
  attempt to use zero-length variable name
Error : unable to load R code in package 'globalVar'
ERROR: lazy loading failed for package 'globalVar'
* removing 'C:/Users/*masked*/Documents/R/win-library/3.2/globalVar'

Exited with status 1.

如何更改上述代码以成功构建一个包,我稍后可以调用setA("apple")getA()实际返回[1] "apple"

2 个答案:

答案 0 :(得分:1)

为什么不使用这样的闭包:

getterSetter<-  function(){

    # define a variable X in the current closure
    x = NULL

    # return a list with two functions:

    list(# The first function returns the value of X defined 
         # when `getterSetter` is called
         get=function()x,
         # and the second function uses the scoping assignment operator to 
         # assign to the variable
         set=function(x)x <<-x)
}


A = getterSetter()
B = getterSetter()

A$set('apple')
B$set('banana')

A$get()
#> [1] "apple"
B$get()
#> [1] "banana"

答案 1 :(得分:1)

可以访问类似于列表的环境,这样可以避免使用getassign,并且可以使一切变得更简单。我想你的assign电话中的论据可能会被颠倒过来。你是否真的想要创建一个没有名称的变量(&#34;&#34;),其值为&#34; alpha&#34;?或者您是否正在尝试创建名为&#34; alpha&#34;的变量?并在(&#34;&#34;)?

中给出它的值

尝试以下替代方案:

gEnv <- new.env()

a <- ""
b <- "Beta"
gEnv[['alpha']] <- a
gEnv[['beta']] <- b

getA <- function()
{
  return(gEnv[['alpha']])
}

getB <- function()
{
  return(gEnv[['beta']])
}

setA <- function(x)
{
  gEnv[['alpha']] <- x
}

setB <- function(x)
{
  gEnv[['beta']] <- x
}