R使用管道运算符时的条件评估%>%

时间:2015-06-02 18:44:42

标签: r dplyr ggvis magrittr

将管道操作符%>%dplyrggvisdycharts等包一起使用时,如何有条件地执行某个步骤?例如;

step_1 %>%
step_2 %>%

if(condition)
step_3

这些方法似乎不起作用:

step_1 %>%
step_2 
if(condition) %>% step_3

step_1 %>%
step_2 %>%
if(condition) step_3

还有很长的路要走:

if(condition)
{
step_1 %>%
step_2 
}else{
step_1 %>%
step_2 %>%
step_3
}

没有所有冗余,是否有更好的方法?

5 个答案:

答案 0 :(得分:69)

以下是利用.ifelse

的快速示例
X<-1
Y<-T

X %>% add(1) %>% { ifelse(Y ,add(.,1), . ) }

ifelse中,如果YTRUE,则会添加1,否则只会返回X的最后一个值。 .是一个替代函数,它告诉函数链的前一步的输出去哪里,所以我可以在两个分支上使用它。

修改  正如@BenBolker指出的那样,您可能不需要ifelse,所以这里是if版本。

X %>% 
add(1) %>% 
 {if(Y) add(.,1) else .}

感谢@Frank指出我应该在{if语句周围使用ifelse括号来继续链接。

答案 1 :(得分:23)

我认为这是purrr::when的情况。如果总和低于25,我们总结一些数字,否则返回0。


library("magrittr")
1:3 %>% 
  purrr::when(sum(.) < 25 ~ sum(.), 
              ~0
  )
#> [1] 6

when返回第一个有效条件的操作产生的值。将条件放在~的左侧,将操作放在右侧。上面,我们只使用了一个条件(然后是其他情况),但是你可以有很多条件。

您可以轻松地将其整合到更长的管道中。

答案 2 :(得分:12)

对我来说,从管道中退出一点点(虽然我有兴趣看到其他解决方案)对我来说似乎是最容易的,例如:

library("dplyr")
z <- data.frame(a=1:2)
z %>% mutate(b=a^2) -> z2
if (z2$b[1]>1) {
    z2 %>% mutate(b=b^2) -> z2
}
z2 %>% mutate(b=b^2) -> z3

这是@ JohnPaul答案的略微修改(你可能不会 真的想要ifelse,它会评估它的两个参数 并且是矢量化的)。修改它以返回会很好 如果条件为假,则自动.警告:我认为这有效,但尚未经过考验/思考 太多了...)

iff <- function(cond,x,y) {
    if(cond) return(x) else return(y)
}

z %>% mutate(b=a^2) %>%
    iff(cond=z2$b[1]>1,mutate(.,b=b^2),.) %>%
 mutate(b=b^2) -> z4

答案 3 :(得分:11)

以下是@JohnPaul提供的答案的变体。此变体使用`if`函数而不是复合if ... else ...语句。

library(magrittr)

X <- 1
Y <- TRUE

X %>% `if`(Y, . + 1, .) %>% multiply_by(2)
# [1] 4

请注意,在这种情况下,`if`函数周围不需要花括号,ifelse语句周围不需要if ... else ...函数。但是,如果点占位符仅出现在嵌套函数调用中,则 magrittr 将默认将左侧管道输入右侧的第一个参数。通过将表达式括在花括号中来覆盖此行为。注意这两个链之间的区别:

X %>% `if`(Y, . + 1, . + 2)
# [1] TRUE
X %>% {`if`(Y, . + 1, . + 2)}
# [1] 4

点占位符在`if`函数中显示的时间内嵌套在函数调用中,因为. + 1. + 2被解释为`+`(., 1)和{{1} }, 分别。所以,第一个表达式返回`+`(., 2)的结果,(奇怪的是,`if`(1, TRUE, 1 + 1, 1 + 2)没有抱怨额外的未使用的参数),第二个表达式返回`if`的结果,在这种情况下,这是期望的行为。

有关 magrittr 管道运算符如何处理点占位符的详细信息,请参阅`if`(TRUE, 1 + 1, 1 + 2)的{​​{3}},特别是“将点用于次要目的”部分”

答案 4 :(得分:2)

我喜欢purrr::when,这里提供的其他基本解决方案都很棒,但是我想要更紧凑,更灵活的东西,所以我设计了函数pif(如果是管道的话),请参见代码和文档的结尾答案。

参数可以是函数的表达式(支持公式表示法),并且如果条件为FALSE,则输入在默认情况下将保持不变。

用于其他答案的示例:

## from Ben Bolker
data.frame(a=1:2) %>% 
  mutate(b=a^2) %>%
  pif(~b[1]>1, ~mutate(.,b=b^2)) %>%
  mutate(b=b^2)
#   a  b
# 1 1  1
# 2 2 16

## from Lorenz Walthert
1:3 %>% pif(sum(.) < 25,sum,0)
# [1] 6

## from clbieganek 
1 %>% pif(TRUE,~. + 1) %>% `*`(2)
# [1] 4

# from theforestecologist
1 %>% `+`(1) %>% pif(TRUE ,~ .+1)
# [1] 3

其他示例:

## using functions
iris %>% pif(is.data.frame, dim, nrow)
# [1] 150   5

## using formulas
iris %>% pif(~is.numeric(Species), 
             ~"numeric :)",
             ~paste(class(Species)[1],":("))
# [1] "factor :("

## using expressions
iris %>% pif(nrow(.) > 2, head(.,2))
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa

## careful with expressions
iris %>% pif(TRUE, dim,  warning("this will be evaluated"))
# [1] 150   5
# Warning message:
# In inherits(false, "formula") : this will be evaluated
iris %>% pif(TRUE, dim, ~warning("this won't be evaluated"))
# [1] 150   5

功能

#' Pipe friendly conditional operation
#'
#' Apply a transformation on the data only if a condition is met, 
#' by default if condition is not met the input is returned unchanged.
#' 
#' The use of formula or functions is recommended over the use of expressions
#' for the following reasons :
#' 
#' \itemize{
#'   \item If \code{true} and/or \code{false} are provided as expressions they 
#'   will be evaluated wether the condition is \code{TRUE} or \code{FALSE}.
#'   Functions or formulas on the other hand will be applied on the data only if
#'   the relevant condition is met
#'   \item Formulas support calling directly a column of the data by its name 
#'   without \code{x$foo} notation.
#'   \item Dot notation will work in expressions only if `pif` is used in a pipe
#'   chain
#' }
#' 
#' @param x An object
#' @param p A predicate function, a formula describing such a predicate function, or an expression.
#' @param true,false Functions to apply to the data, formulas describing such functions, or expressions.
#'
#' @return The output of \code{true} or \code{false}, either as expressions or applied on data as functions
#' @export
#'
#' @examples
#'# using functions
#'pif(iris, is.data.frame, dim, nrow)
#'# using formulas
#'pif(iris, ~is.numeric(Species), ~"numeric :)",~paste(class(Species)[1],":("))
#'# using expressions
#'pif(iris, nrow(iris) > 2, head(iris,2))
#'# careful with expressions
#'pif(iris, TRUE, dim,  warning("this will be evaluated"))
#'pif(iris, TRUE, dim, ~warning("this won't be evaluated"))
pif <- function(x, p, true, false = identity){
  if(!requireNamespace("purrr")) 
    stop("Package 'purrr' needs to be installed to use function 'pif'")

  if(inherits(p,     "formula"))
    p     <- purrr::as_mapper(
      if(!is.list(x)) p else update(p,~with(...,.)))
  if(inherits(true,  "formula"))
    true  <- purrr::as_mapper(
      if(!is.list(x)) true else update(true,~with(...,.)))
  if(inherits(false, "formula"))
    false <- purrr::as_mapper(
      if(!is.list(x)) false else update(false,~with(...,.)))

  if ( (is.function(p) && p(x)) || (!is.function(p) && p)){
    if(is.function(true)) true(x) else true
  }  else {
    if(is.function(false)) false(x) else false
  }
}