I recently wrote a package to solve the Twitter Waterflow Problem using an R6
class. You can view the package here and read about how I approached the problem here. In this blog post, I want to highlight how you can access private
members of an R6
class which Winston Chang mentioned in his useR!2017 talk. I will use the waterflow
package for this example. Within the R6
waterflow class there is a private
member function, or method, that converts the data you provide the class with, and the data it calculates, into a tidy data.frame
used for generating a plot. However what if we already have the data that this function needs to be supplied with? How can we just run this function on the fly? If we try to call it directly, we get an error.
library(waterflow)
wall <- c(2, 5, 1, 2, 3, 4, 7, 7, 6)
water <- c(2, 5, 1, 2, 3, 4, 7, 7, 6)
p <- waterflow$new(wall)
p$tidyWater(water, wall)
# Error in eval(expr, envir, enclos): attempt to apply non-function
Instead, what we need to do is extract the method from the class’ environment, .__enclos_env__
, which allows us access to private
members of the class.
p$.__enclos_env__$private$tidyWater(water, wall)
# pos type val
# 1 1 water 2
# 2 2 water 5
# 3 3 water 1
# 4 4 water 2
# 5 5 water 3
# 6 6 water 4
# 7 7 water 7
# 8 8 water 7
# 9 9 water 6
# 10 1 wall 2
# 11 2 wall 5
# 12 3 wall 1
# 13 4 wall 2
# 14 5 wall 3
# 15 6 wall 4
# 16 7 wall 7
# 17 8 wall 7
# 18 9 wall 6