1

在阅读了很多堆栈溢出问题后,我对全局变量赋值有点困惑。我已经研究过 R 中的全局变量和其他类似的问题

我有以下情况。我有 2 个全局变量current_idxprevious_idx. 这两个全局变量由引用类中的方法设置。

本质上,使用<<-赋值运算符应该可以正常工作吗?但是,我收到了这个警告

Non-local assignment to non-field names (possibly misspelled?)

我哪里错了?

编辑

使用assign(current_idx, index, envir = .GlobalEnv)作品,即我没有收到警告。有人可以对此有所了解。

4

2 回答 2

4

You are confusing "global variables" and Reference Classes which are a type of environment. Executing <<- will assign to a variable with that name in the parent.frame of the function. If you are only one level down from the .GlobalEnv, it will do the same thing as your assign statement.

If you have a Reference Class item you can assign items inside it by name with:

ref_item$varname <- value

Easier said than done, though. First you need to set up the ReferenceClass properly:

http://www.inside-r.org/r-doc/methods/ReferenceClasses

于 2013-01-25T19:40:18.717 回答
2

发生这种情况是因为从引用类方法中修改引用类字段的默认方法是使用<<-. 例如,在:

setRefClass(
  "myClass", 
  fields=list(a="integer"), 
  methods=list(setA=function(x) a <<- x)
)

您可以通过该方法修改a参考类的字段。setA因为这是通过引用类中的方法设置字段的规范方式,所以 R 假定<<-在引用方法中的任何其他使用都是错误的。因此,如果您尝试分配存在于引用类以外的环境中的变量,R“有用地”警告您可能有错字,因为它认为<<-在引用方法中唯一可能使用的是修改引用字段.

您仍然可以使用<<-. 警告只是一个警告,也许你正在做一些你不打算做的事情。如果您打算写入全局环境中的对象,则警告不适用。

通过使用assign,您绕过了引用方法执行的检查,以确保您不会在引用方法的赋值中意外输入字段名称,因此您不会收到警告。另外,请注意,它assign实际上以您提供的环境为目标,而<<-只会在词法搜索路径中找到该名称的第一个对象。

综上所述,在极少数情况下,您实际上希望引用方法确实直接写入全局环境。你可能需要重新考虑你在做什么。您应该问自己为什么这两个变量不仅仅是引用类中的字段而不是全局变量。

于 2016-10-13T01:01:41.743 回答