我有一个 R6 类,其中包含一系列用于进行例行检查的辅助函数。这些函数存在于公共列表中,通常采用单个参数,对传递给单个参数的值进行一些检查,如果没有错误,则返回该值。我经常使用多项检查是很常见的。
我想magrittr
用来使这些测试更容易链接在一起,是否可以使用该with
功能进一步缩短代码
library(magrittr)
library(R6)
test = R6::R6Class("Test",inherit=NULL,
public = list(
initialize = function(){
},
fA = function(x){
writeLines("Called FA")
x
},
fB = function(x){
writeLines("Called FB")
x
},
#Enable Chaining by Returning Invisible copy of the R6 Instance
fC = function(x){
writeLines("Called FC")
invisible(self)
},
fD = function(x){
writeLines("Called FD")
invisible(self)
}
)
)
#Works as expected
x = test$new()
y <- 1 %>% x$fA() %>% x$fB()
y
#This is also possible, but it loses the desired return value, and the value of the argument
#needs to be explicitly passed through to each function.
x$fC(1)$fD(1)
#I Would Like to do something like this:
y <- with(x,1 %>% fA() %>% fB()) #ERROR, could not find function "%>%"
#Trying to resolve the above, I also tried this, which doesn't work.
y <- with(x,1 magrittr::`%>%` fA() magrittr::`%>%` fB()) #ERROR
如何让%>%
操作员在with
函数中得到认可?