【问题标题】:Formals within R6ClassR6Class 中的形式
【发布时间】:2015-07-30 15:47:27
【问题描述】:

我正在尝试在 R6Class 中获取函数的formals()。但这似乎不起作用。我认为环境可能存在问题。

Test <- R6Class(
  "Test",

  public = list(
    foo = function(x){
      x
    }, 

    printFormals1 = function(){
      formals("foo")
    }, 

    printFormals2 = function(){
      formals("self$foo")
    }
  )
)

test <- Test$new()
test$printFormals1()
test$printFormals2()

错误提示:

Error in get(fun, mode = "function", envir = parent.frame()) : 
  object 'foo' of mode 'function' was not found

Error in get(fun, mode = "function", envir = parent.frame()) : 
  object 'self$foo' of mode 'function' was not found

没有 R6Classes 这很容易:

foo <- function(x){
  x
}

formals("foo")

结果:

$x

很高兴有人能解释和帮助

谢谢 迈克尔

编辑:

找到了解决办法。与 R6class 无关: eval(parse(text = "self$foo")) 完成了这项工作。我会留下这个问题,以防其他人遇到类似的问题。

Test <- R6Class(
  "Test",

  public = list(
    foo = function(x){
      x
    }, 

    printFormals2 = function(){
      print(formals(eval(parse(text = "self$foo"))))
    }
  )
)

test <- Test$new()

test$printFormals2()

【问题讨论】:

    标签: r r6


    【解决方案1】:

    查看formals 的内部结构,您会发现它具有非常具体的搜索参数,用于当您传递字符而非函数的内容时。

    你可以只传递函数[避免eval(parse(text=...))丑陋]

    Test <- R6Class(
      "Test",
    
      public = list(
        foo = function(x){
          x
        }, 
    
        printFormals2 = function(){
         formals(self$foo)
        }
      )
    )
    
    test <- Test$new()
    
    test$printFormals2()
    # $x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多