Samir Malik
Samir Malik

Reputation: 1

Calling R6 method dynamically where method name is stored in string variable

How do you call a R6 method dynamically i.e the method name is held as a string variable:

Test <- R6Class("Test",
  public = list(
      char_to_upper = function(var) { toupper(var) }
  ))

# create test object
test_obj <- Test$new()

# method name store in variable
method_to_call <- "char_to_upper"

# call method
test_obj$method_to_call("hello")

Upvotes: 0

Views: 208

Answers (1)

MrFlick
MrFlick

Reputation: 206207

You can use

test_obj[[method_to_call]]("hello")

In general you want to use [[]] when sub-setting with variables. $ only works with literal values.

Upvotes: 0

Related Questions