当函数名存储在变量中时,我在 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
任何指针都会很棒!
使用[[
代替$
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>
它只返回函数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句