psteelk psteelk - 10 months ago 44
R Question

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

. 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 ?


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

42- 42-
Answer Source

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: