0

I have a R6 class with code like this

# Cutting out lots of code and only putting in relevant lines
public(
   function1 <- function(){
      var <- xyz$abc
   },

  function2 <- function(){
     xyz <- blah blah
     z <- function1()
  }
)

When calling function2 I get an error in function1 saying that xyz is not found even though its assigned in function2 which is called before function1

Please let me know if I am understanding this correctly and how to fix it.

1 Answers1

0

For "traditional" R functions the parent of the evaluation environment of a function is the calling environment.

For R6 function this not the same. The parent of the evaluation environment of a method is an environment enclosing the self variable that gives access to object properties.

You can test this by adding

print(ls(parent.env(environment()))) in your method.

This means that you can't have access to your xyz variable in function1. You must use public or private variables or pass it as a parameter to your function.

By the way you must also prepend self$ to the call of function1 (self$function1())

Billy34
  • 1,777
  • 11
  • 11
  • That's not true about regular closures. The environment of the function (what you're calling the parent) is the environment where the function was created. It is the parent of the evaluation frame (what you're calling the environment). Confusingly, the `environment()` function returns the evaluation frame when you run it in a function. – user2554330 May 04 '20 at 10:03
  • Good point. I tested with rlang::caller_env and somewhat get lost when trying to symplify the answer. – Billy34 May 04 '20 at 10:49