eapie
eapie

Reputation: 53

How to call a function of a class when the function name is stored in a variable

I have hit a problem in R trying to call a function when the function name is stored in a variable. From the forum I can see that get(funcName) would work but what if the function is in a reference class?

Example below:

TestClass <- setRefClass("TestClass", 
                        fields = c("x", "y"),
                        methods = list(
                          say_hello = function() message("Hi")
                        )
)
myTest <- TestClass(x=2, y=3)
myTest$say_hello()  # works ok

# Now i'd like to use the call by using the name of the function in a variable
funcName <- "say_hello"

get(funcName) # this would work if not a class
get(funcName,myTest) #this gives me the function definition and does not run the function

Any pointers would be great!

Upvotes: 4

Views: 45

Answers (1)

akrun
akrun

Reputation: 887008

Use [[ instead of $

myTest[[funcName]]()
Hi

With get, we need to do the invocation

get(funcName, myTest)()
Hi

Similar to

myTest$say_hello()

i.e. if we do

myTest$say_hello
Class method definition for method say_hello()
function () 
message("Hi")
<environment: 0x7fbbc326b390>

it returns only the function

Upvotes: 2

Related Questions