[英]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.