自定义管道使警告静音 [英] Custom pipe to silence warnings

查看:82
本文介绍了自定义管道使警告静音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题有关。

我想构建一个自定义管道%W>%,该管道将使一项操作的警告静音

I'd like to build a custom pipe %W>% that would silence warnings for one operation

library(magrittr)
data.frame(a= c(1,-1)) %W>% mutate(a=sqrt(a)) %>% cos

将等同于:

w <- options()$warn
data.frame(a= c(1,-1)) %T>% {options(warn=-1)} %>%
  mutate(a=sqrt(a))    %T>% {options(warn=w)}  %>%
  cos

这两次尝试均无效:

`%W>%` <- function(lhs,rhs){
  w <- options()$warn
  on.exit(options(warn=w))
  options(warn=-1)
  lhs %>% rhs
}

`%W>%` <- function(lhs,rhs){
  lhs <- quo(lhs)
  rhs <- quo(rhs)
  w <- options()$warn
  on.exit(options(warn=w))
  options(warn=-1)
  (!!lhs) %>% (!!rhs)
}

如何将 rlang 变成有效的东西?

How can I rlang this into something that works ?

推荐答案

我想我将通过调整magrittr管道以包含此新选项的方式来实现。这种方法应该非常健壮。

I think I would approach it like this, by tweaking the magrittr pipes to include this new option. This way should be pretty robust.

首先,我们需要在magrittr函数 is_pipe 中插入一个新选项。确定某个功能是否为管道。我们需要它来识别%W>%

First we need to insert a new option into magrittr's function is_pipe by which it is determined whether a certain function is a pipe. We need it to recognise %W>%

new_is_pipe = function (pipe)
{
  identical(pipe, quote(`%>%`)) || identical(pipe, quote(`%T>%`)) ||
    identical(pipe, quote(`%W>%`)) ||
    identical(pipe, quote(`%<>%`)) || identical(pipe, quote(`%$%`))
}
assignInNamespace("is_pipe", new_is_pipe, ns="magrittr", pos="package:magrittr")
`%W>%` = magrittr::`%>%`

我们还需要一个新的辅助函数检查正在处理的管道是否为%W>%

We also need a new helper function that checks whether the pipe being processed is a %W>%

is_W = function(pipe) identical(pipe, quote(`%W>%`))
environment(is_W) = asNamespace('magrittr')

最后,我们需要在 magrittr ::: wrap_function 中放入一个新分支,以检查这是否是%W>%管道。如果是这样,它将 options(warn = -1) on.exit(options(warn = w)插入函数调用的主体。

Finally, we need to put a new branch into magrittr:::wrap_function which checks if this is a %W>% pipe. If so, it inserts options(warn = -1) and on.exit(options(warn = w) into the body of the function call.

new_wrap_function = function (body, pipe, env)
{
  w <- options()$warn
  if (magrittr:::is_tee(pipe)) {
    body <- call("{", body, quote(.))
  }
  else if (magrittr:::is_dollar(pipe)) {
    body <- substitute(with(., b), list(b = body))
  }
  else if (is_W(pipe)) {
    body <- as.call(c(as.name("{"), expression(options(warn=-1)), parse(text=paste0('on.exit(options(warn=', w, '))')), body))
  }
  eval(call("function", as.pairlist(alist(. = )), body), env, env)
}
assignInNamespace("wrap_function", new_wrap_function, ns="magrittr", pos="package:magrittr")

对此功能进行测试:

data.frame(a= c(1,-1)) %W>% mutate(a=sqrt(a)) %>% cos
#           a
# 1 0.5403023
# 2       NaN

相比...

data.frame(a= c(1,-1)) %>% mutate(a=sqrt(a)) %>% cos
#           a
# 1 0.5403023
# 2       NaN
# Warning message:
# In sqrt(a) : NaNs produced

这篇关于自定义管道使警告静音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆