使用set动态构造R6class和instance

Using set to dynamically construct R6 class and instance

我想创建一个动态创建 R6 class 和实例对象的函数 create_thresholds。这个想法是 动态创建一个数据结构,该数据结构具有只读活动字段 客户端对象可以访问类似于 Wickham 说明的示例(https://adv-r.hadley.nz/r6.html - 16.3.2 Active fields). I've looked at dynamically add function to r6 class instance 但我正在寻找修改 class 定义的解决方案,而不是向实例对象添加函数。

函数 create_thresholds 读取 data.frame 个 var/val 对,然后创建一个 R6Class 对象,它试图在该对象上设置各种私有字段并创建只读活动字段。该函数通过创建 Thresholds 对象的新实例而终止。

如下面的代码所示,调用活动方法似乎是在不正确的环境中计算方法表达式。

library("R6")


create_thresholds <- function(df) {
  require(glue)
  Thresholds <- R6Class("Thresholds")

    for (i in 1:nrow(df)){
      e <- environment()
      print(e)
      Thresholds$set("private", glue(".{df$var[i]}"), df$val[i])
      Thresholds$set("active", glue("{df$var[i]}"), function() {
        eval(parse(text = glue("private$.{df$var[i]}")))
      })
    }

  th <- Thresholds$new()

  return(th)
}

df <- tibble::tribble(~var, ~val,
                      "min_units", 100,
                      "min_discount", 999)


th <- create_thresholds(df)
th$min_discount ## expect 999
th$min_units ## OOPS! expect 100

以下解决方案需要动态创建整个 function/method 定义的字符串形式,然后对其调用 eval(parse())

library("R6")


df <- tibble::tribble(~var, ~val,
                      "min_units", 100,
                      "min_discount", 999)

create_thresholds <- function(df) {
  Thresholds <- R6Class("Thresholds")

  for (i in 1:nrow(df)){
    mthd_name <- df$var[i]
    mthd_def <- glue::glue("function() private$.{mthd_name}")
    Thresholds$set("private", glue(".{mthd_name}"), df$val[i])
    Thresholds$set("active", mthd_name, eval(parse(text = mthd_def)))
  }

  hh <- Thresholds$new()
  return(hh)
}

hh <- create_thresholds(df)
hh$min_discount # expect 999!
hh$min_units #expect 100