1

我有一个 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函数中得到认可?

4

1 回答 1

0

我在这里发布了一个类似的解决方案。问题在于,with将您的代码x用作一个环境,其中唯一定义的函数是x. 访问管道的一种方法是将其定义为附加方法(这很棘手),但您也可以将其设置.GlobalEnv为 的临时父环境x,这意味着您可以在 中正常使用其他功能with

parent.env(x) <- .GlobalEnv
with(x, 1 %>% fA() %>% fB())
parent.env(x) <- emptyenv() # removes the parent environment

您也可以将其包装在一个函数中,这样您就不必每次都手动设置和重置父环境:

with_global <- function(object, task_expr) {
  task_expr <- substitute(task_expr)
  parent.env(object) <- rlang::current_env()
  with(object, eval(task_expr))
于 2020-07-26T11:41:16.760 回答