Search code examples
rclassr6

Accessing R6 class variable when variable name is not known advance?


Here's a simple code, which illustrates what I'd like to achieve:

require(R6)
cTest <- R6Class(
  "CTest", 
  public = list(
    a = 10, b=20, c=30,
    printX = function(x) {
      print(self[x])
    }
  )
) #"CTest"

myClass <- cTest$new(); 
for (x in c("a","b", "c"))
   myClass$printX("a")

And it does not work. Error message:

"Error in self[x] : object of type 'environment' is not subsettable"

For comparison, the similar task for lists/data.frames works:

for (x in c("mpg","cyl", "hp"))
   print(mtcars[x])

Can you help?


Solution

  • This seems to work fine if you use double-bracket indexing (i.e., print(self[[x]])). The problem is that in general single-bracket indexing tries to extract a subset of the original object; in contrast double-bracket indexing extracts an element of the original object. For example, if L is a list of numbers, L[x] is a sub-list, while L[[x]] is a number. From Hadley Wickham on twitter:

    enter image description here