首页 > 解决方案 > 当函数名存储在变量中时如何调用类的函数

问题描述

当函数名称存储在变量中时,我在 R 中尝试调用函数时遇到了问题。从论坛我可以看到 get(funcName) 可以工作,但如果该函数在引用类中怎么办?

下面的例子:

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

任何指针都会很棒!

标签: rfunctionclass

解决方案


使用[[代替$

myTest[[funcName]]()
Hi

get我们需要进行调用

get(funcName, myTest)()
Hi

如同

myTest$say_hello()

即如果我们这样做

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

它只返回函数


推荐阅读