我希望能够在 R 中创建一个具有两个“层”函数的对象。我在下面使用 S4 类整理了一个非常基本的示例。
setClass("2layer_obj",
slots = list(
lower_functions = "list",
higher_functions = "list"
)
)
lower_functions <- list(
function1 = function(x){
x+2
},
function2 = function(y){
y+6
}
)
higher_functions <- list(
function3 = function(z){
test_obj@lower_functions$function1(z)+test_obj@lower_functions$function2(z)
},
function4 = function(z){
test_obj@lower_functions$function1(z)-test_obj@lower_functions$function2(z)
}
)
test_obj <- new("2layer_obj",
lower_functions = lower_functions,
higher_functions = higher_functions
)
rm(lower_functions)
rm(higher_functions)
test_obj@higher_functions$function3(7)
我的问题是,为了让这段代码工作,我必须test_obj@在lower_functions$function1(z). 因此,如果我要重新运行此代码但更改
test_obj <- new("2layer_obj",
lower_functions = lower_functions,
higher_functions = higher_functions
)
至
test_obj2 <- new("2layer_obj",
lower_functions = lower_functions,
higher_functions = higher_functions
)
并试图运行test_obj2@higher_functions$function3(7)
它不起作用,因为
Error in test_obj2@higher_functions$function3(7) :
object 'test_obj' not found
所以,我的问题是如何在 R 中创建一个对象(使用任何 OO 类系统),其中一个插槽中的函数可以在另一个插槽中运行函数而无需使用对象的名称?