Custom pipe to silence warnings

后端 未结 4 492
孤城傲影
孤城傲影 2020-12-30 04:28

Related to this question.

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

library(magrittr)
data.         


        
4条回答
  •  借酒劲吻你
    2020-12-30 04:42

    Perhaps something like this with rlang:

    library(rlang)
    library(magrittr)
    
    `%W>%` <- function(lhs, rhs){
      w <- options()$warn
      on.exit(options(warn=w))
      options(warn=-1)
      lhs_quo = quo_name(enquo(lhs))
      rhs_quo = quo_name(enquo(rhs))
      pipe = paste(lhs_quo, "%>%", rhs_quo)
      return(eval_tidy(parse_quosure(pipe)))
    }
    
    data.frame(a= c(1,-1)) %W>% mutate(a=sqrt(a)) %>% cos
    

    Result:

              a
    1 0.5403023
    2       NaN
    

    Note:

    • You need enquo instead of quo because you are quoting the code that was supplied to lhs and rhs, not the literals lhs and rhs.

    • I couldn't figure out how to feed lhs_quo/lhs into rhs_quo (which was a quosure) before it was evaluated, neither can I evaluate rhs_quo first (throws an error saying a not found in mutate(a=sqrt(a)))

    • The workaround that I came up with turns lhs and rhs into strings, pastes them with "%>%", parses the string to quosure, then finally tidy evaluates the quosure.

提交回复
热议问题