Search code examples
rr6

Formals within R6Class


I'm trying to get the formals() of a function within an R6Class. But this does not seem to work. I think there might be a problem with the environments.

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()

The error says:

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

Without R6Classes this is easy:

foo <- function(x){
  x
}

formals("foo")

resulting:

$x

Glad if someone could explain and help

Thank you Michael

edit:

Found the solution. Not related to R6class: eval(parse(text = "self$foo")) does the job. I'm leaving the question in case someone else faces a similar problem.

Test <- R6Class(
  "Test",

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

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

test <- Test$new()

test$printFormals2()

Solution

  • Looking under the hood of formals you will see that it has very specific search paramaters for when you pass something that is a character not a function.

    You can just pass the function [avoiding the eval(parse(text=...)) ugliness]

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