【问题标题】:Can you use helper functions inside R6 objects?你可以在 R6 对象中使用辅助函数吗?
【发布时间】:2020-02-17 13:40:12
【问题描述】:

我试图避免在 R6 对象内重复。每次更新输入之一时,都必须更新计算/派生值。

下面的Cube 对象演示了这个问题。如果我更新widthheightdepth 中的任何一个,则必须更新volume

在这种情况下,公式是微不足道的,但在实际情况中并非总是如此。是否可以将volCalc 的知识存储在某个地方,并允许set_width 在更新时使用该功能更新volume

现在,我可以使用下面的对象代码创建对象:

R> cc <- Cube$new(width = 5, height = 6, depth = 7)

但更新时会中断

R> cc$set_width(10)
Error in volCalc(self$width, self$height, self$depth) : 
  could not find function "volCalc"

如你所见,我把如何计算立方体(volCalc)体积的知识放在了两个地方;但是唉cc$set_width和朋友都找不到...

Cube <- R6Class("Cube",
  public = list(
    width = NULL,
    height = NULL,
    depth = NULL,
    volume = NULL,

    initialize = function(width, height, depth) {
      self$width <- width
      self$height <- height
      self$depth <- depth

      volCalc = function(W, H, D) W * H * D

      self$volume <- volCalc(width, height, depth)
    },

    volCalc = function(W, H, D) {
      self$volume <- W * H * D
      invisible(self)
    },    

    set_width = function(nWidth) {
      self$width <- nWidth
      volCalc(self$width, self$height, self$depth)
      invisible(self)
    },

    set_height = function(nHeight) {
      self$height <- nHeight
      volCalc(self$height, self$height, self$depth)
      invisible(self)
    },

    set_depth = function(nDepth) {
      self$depth <- nDepth
      volCalc(self$depth, self$depth, self$depth)
      invisible(self)
    }
  )
)

【问题讨论】:

    标签: r r6


    【解决方案1】:

    你需要告诉你的班级在哪里可以找到volCalc。它会在self 中找到它。因此,您需要做的就是将内部调用volCalc 变为self$volCalc。然后你可以这样做:

    cc <- Cube$new(width = 5, height = 6, depth = 7)
    cc
    #> <Cube>
    #>   Public:
    #>     clone: function (deep = FALSE) 
    #>     depth: 7
    #>     height: 6
    #>     initialize: function (width, height, depth) 
    #>     set_depth: function (nDepth) 
    #>     set_height: function (nHeight) 
    #>     set_width: function (nWidth) 
    #>     volCalc: function (W, H, D) 
    #>     volume: 210
    #>     width: 5
    
    cc$set_width(10)
    cc
    #> <Cube>
    #>   Public:
    #>     clone: function (deep = FALSE) 
    #>     depth: 7
    #>     height: 6
    #>     initialize: function (width, height, depth) 
    #>     set_depth: function (nDepth) 
    #>     set_height: function (nHeight) 
    #>     set_width: function (nWidth) 
    #>     volCalc: function (W, H, D) 
    #>     volume: 420
    #>     width: 10
    

    【讨论】:

    • 啊...稍微摆弄一下,我发现它也可以在 initialize 函数中使用;一旦我删除了函数的invisible(self) 行。
    猜你喜欢
    • 2019-08-02
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2021-09-26
    • 2018-05-08
    • 2019-01-17
    相关资源
    最近更新 更多