我希望能够在我的 R6 类中重新定义公共方法(以便它根据该类保存的数据类型进行更改) - 如下所示
library(R6)
Simple <- R6Class(
"Simple",
public = list(
dt = mtcars,
my.print = function (){
print(self$dt$mpg)
}
)
)
s <- Simple$new()
s$my.print()
s$dt <- iris
s$my.print() <- function() {
print(self$dt$Species)
}
上面的代码给出了错误:
Error in s$my.print() <- function() { :
invalid (NULL) left side of assignment
或者,我知道我可以这样做:
Simple$set("public", "my.print2", function {
print(self$dt$Species) } )
但这也不合适,因为每次这样做我都必须重新初始化我的课程。
有没有适当的方法可以做到这一点?
想法取自动态添加函数到r6类实例 https://stackoverflow.com/questions/26331030/dynamically-add-function-to-r6-class-instance那怎样才能达到我们想要的效果呢。
这有点棘手,因为您需要注意以下几点:
- 首先,您需要将函数声明为类成员变量,而不是方法(函数)
- 然后这个变量将成为一个函数,当你这样分配时
- 该函数接收输入参数 - 类本身(
self
)
Simple <- R6Class(
"Simple",
public = list(
dt = mtcars,
my.print = NULL
)
)
s <- Simple$new()
s$my.print
s$my.print(s)
s$dt <- iris
s$my.print <- function(self) {
print(self$dt$Species %>% unique)
}
s$my.print
s$my.print(s)
上述代码的输出如下:
> Simple <- R6Class(
+ "Simple",
+ public = list(
+ dt = mtcars,
+ my.print = NULL
+ )
+ )
> s <- Simple$new()
> s$my.print
NULL
> s$my.print(s)
Error: attempt to apply non-function
> s$my.print
NULL
> s$my.print(s)
Error: attempt to apply non-function
> s$dt <- iris
> s$my.print <- function(self) {
+ print(self$dt$Species %>% unique)
+ }
>
> s$my.print
function(self) {
print(self$dt$Species %>% unique)
}
> s$my.print(s)
[1] setosa versicolor virginica
Levels: setosa versicolor virginica
>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)