r - 当函数名存储在变量中时如何调用类的函数
问题描述
当函数名称存储在变量中时,我在 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>
它只返回函数
推荐阅读
- ios - iOS App starts crashing after a week of installing it to device
- angular - 拥有一个打字稿类的属性取决于另外两个,如何进行?
- python - Find matching values in two pandas dataframes and return a value from the matching row
- javascript - 如何从对象数组中填充多个输入字段
- java - 具有固定初始值的累积差
- kotlin - Kotlin 是否有与 swift 中的“DispatchWorkItem”完全相同的东西?
- html - 网站 no_id yes_class getelement 然后点击
- javascript - Mock imported function with jest in an await context
- javascript - Asynchronous code in nested forEach loop- react native
- python - AttributeError when using ColumnTransformer into a pipeline