Question

I'm a bit confused on global variable assignments after reading quite a lot of stack overflow questions. I have gone through Global variables in R and other similar questions

I have the following situation. I have 2 global variables current_idx and previous_idx. These 2 global variables are being set by a method in a reference class.

Essentially, using <<- assignment operator should work right ? But, I get this warning

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

Where am I going wrong ?

EDIT

Using assign(current_idx, index, envir = .GlobalEnv) works i.e. I do not get the warning. Can some one shed some light on this.

Was it helpful?

Solution

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

OTHER TIPS

This is happening because the default method for modifying fields of a reference class from within a reference class method is to use <<-. For example, in:

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

You can modify the a field of your reference class via the setA method. Because this is the canonical way of setting fields via methods in reference classes, R assumes that any other use of <<- within a reference method is a mistake. So if you try to assign to a variable that exists in an environment other than the reference class, R "helpfully" warns you that maybe you have a typo since it thinks the only probably use of <<- in a reference method is to modify a reference field.

You can still just assign to global objects with <<-. The warning is just a warning that maybe you are doing something you didn't intend to do. If you intended to write to an object in the global environment, then the warning doesn't apply.

By using assign you are bypassing the check that reference methods carry out to make sure you are not accidentally typoing a field name in an assignment within the reference method, so you don't get the warning. Also, note that assign actually targets the environment you supply, whereas <<- will just find the first object of that name in the lexical search path.

All this said, there are really rare instances where you actually want a reference method do be writing directly to the global environment. You may need to rethink what you are doing. You should ask yourself why those two variables are not just fields in the reference class instead of global variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top