R6Class 中的形式

Formals within R6Class

我正在尝试获取 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()

深入了解 formals,您会发现当您传递字符而非函数时,它具有非常具体的搜索参数。

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

Test <- R6Class(
  "Test",

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

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

test <- Test$new()

test$printFormals2()
# $x