Inside R6 class definition: 'object not found' (or: how to define 'local' objects in R6 classes)

Inside R6 class definition: 'object not found' (or: how to define 'local' objects in R6 classes)

我想定义一个 R6 class 来设置、更新和关闭进度条。对于这 3 个任务,我有 3 个函数。第一个 setup_progressbar() 调用 RtxtProgressbar(),其中 returns 一个需要传递给第二个和第三个的对象(比如 pb)函数,update_progressbar()close_progressbar()。但是后两个函数没有找到对象pb

library(R6)
myprogressbar <- R6Class("my_progress_bar",
                         public = list(
                             n = numeric(1),
                             initialize = function(n) {
                                 stopifnot(n >= 1)
                                 self$n <- n
                             },
                             setup_progressbar = function() {
                                 pb <- txtProgressBar(max = self$n)
                             },
                             update_progressbar = function(i) {
                                 setTxtProgressBar(pb, i)
                             },
                             close_progressbar = function () {
                                 close(pb)
                                 cat("\n")
                             }
                         ))
mypb <- myprogressbar$new(10)
mypb$setup_progressbar()
mypb$update_progressbar(3) # Error in setTxtProgressBar(pb, i) : object 'pb' not found

我试图将 pb 添加到 self,希望它能被找到,但后来我得到了 "cannot add bindings to a locked environment".

注意:在我的实际(非最小)示例中,i 是 found/provided/visible,所以这不是一个额外的问题(很可能这只是上面最小工作示例中的一个问题一旦修复超出 'pb' not found 错误)。

以下作品:

library(R6)
myprogressbar <- R6Class("my_progress_bar",
                         public = list(
                             n = numeric(1),
                             pb = NULL, # provide as argument
                             initialize = function(n, pb = NULL) { # provide with default so that $new() doesn't require 'pb'
                                 stopifnot(n >= 1)
                                 self$n <- n
                             },
                             setup_progressbar = function() {
                                 self$pb <- txtProgressBar(max = self$n)
                             },
                             update_progressbar = function(i) {
                                 setTxtProgressBar(self$pb, i)
                             },
                             close_progressbar = function () {
                                 close(self$pb)
                                 cat("\n")
                             }
                         ))

mypb <- myprogressbar$new(10)
mypb$setup_progressbar()
mypb$update_progressbar(3)