Search code examples
rreference-class

Setting Global variables inside reference class in R


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.


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