[英]Inside R6 class definition: 'object not found' (or: how to define 'local' objects in R6 classes)
我想定义一个设置、更新和关闭进度条的 R6 class。 对于这 3 个任务,我有 3 个功能。 第一个setup_progressbar()
调用R
的txtProgressbar()
,它返回一个 object (比如pb
),它需要传递给第二个和第三个函数update_progressbar()
和close_progressbar()
。 但是后两个函数没有找到 object 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
被发现/提供/可见,所以这不是一个额外的问题(很可能这只是上述最小工作示例中的一个问题,一旦修复超出了'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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.