简体   繁体   English

在R中的新环境中分配值的功能

[英]Function to assign a value in a new environment in R

I'm trying to write a function 'exported' in R that will assign a value to a name in a desired environment (say .GlobalEnv). 我正在尝试在R中编写“导出”函数,该函数将在所需环境中为名称分配一个值(例如.GlobalEnv)。 I'd like to use the following syntax. 我想使用以下语法。

# desired semantics: x <- 60
exported(x) <- 60
# ok if quotes prove necessary.
exported("x") <- 60

I've tried several variations. 我尝试了几种变体。 Most basically: 最基本的:

`export<-` <- function(x, obj) {
  call <- as.list(match.call())
  elem <- as.character(call[[2]])
  assign(elem, obj, .GlobalEnv)
  get(elem, .GlobalEnv)
}
exported(x) <- 50

The foregoing gives an error about the last argument being unused. 前面给出了关于最后一个参数未使用的错误。 The following complains that "object 'x' is not found." 以下内容抱怨“找不到对象'x'”。

setGeneric("exported<-", function(object, ...) {
  standardGeneric("exported<-")
})

setReplaceMethod("exported", "ANY", function(object, func) {
  call <- as.list(match.call())
  name <- as.character(call$object)
  assign(name, func, other.env)
  assign(name, func, .GlobalEnv)
  get(name, .GlobalEnv)
})

exported(x) <- 50

The above approach using a character vector in place of a name yields "target of assignment expands to non-language object." 使用字符向量代替名称的上述方法产生“分配对象扩展为非语言对象”。

Is this possible in R? 在R中这可能吗?


EDIT: I would actually like to do more work inside 'exported.' 编辑:我实际上想在“导出”中做更多的工作。 Code was omitted for brevity. 为了简洁起见,省略了代码。 I also realize I can use do something like: 我也意识到我可以使用类似的方法:

exported(name, func) {
  ...
}

but am interested in seeing if my syntax is possible. 但有兴趣查看我的语法是否可行。

I can't understand why you wouldn't use assign ? 我不明白您为什么不使用assign

assign( "x" , 60 , env = .GlobalEnv )
x
[1] 60

The env argument specifies the environment into which to assign the variable. env参数指定将变量分配到的环境。

e <- new.env()
assign( "y" , 50 , env = e )
ls( env = e )
[1] "y"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM