Accessing Private Methods from an R6 Class

[This article was first published on Random R Ramblings, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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
To leave a comment for the author, please follow the link and comment on their blog: Random R Ramblings.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)