rmf*_*rmf 76 r dplyr ggvis magrittr
当使用管道操作符%>%与包,如dplyr,ggvis,dycharts,等,我该怎么办了一步条件?例如;
step_1 %>%
step_2 %>%
if(condition)
step_3
Run Code Online (Sandbox Code Playgroud)
这些方法似乎不起作用:
step_1 %>%
step_2
if(condition) %>% step_3
step_1 %>%
step_2 %>%
if(condition) step_3
Run Code Online (Sandbox Code Playgroud)
有很长的路要走:
if(condition)
{
step_1 %>%
step_2
}else{
step_1 %>%
step_2 %>%
step_3
}
Run Code Online (Sandbox Code Playgroud)
没有所有冗余,有没有更好的方法?
Joh*_*aul 77
这是一个利用.和的快速示例ifelse:
X<-1
Y<-T
X %>% add(1) %>% { ifelse(Y ,add(.,1), . ) }
Run Code Online (Sandbox Code Playgroud)
在ifelse,如果Y是TRUE,如果将加1,否则将只是返回的最后一个值X.这.是一个替代,告诉函数链的前一步的输出去哪里,所以我可以在两个分支上使用它.
编辑
为@BenBolker指出,你可能不想要ifelse,所以这是一个if版本.
X %>%
add(1) %>%
{if(Y) add(.,1) else .}
Run Code Online (Sandbox Code Playgroud)
感谢@Frank指出我应该{在我if和ifelse语句周围使用大括号来继续链.
Lor*_*ert 27
我认为这是一个例子purrr::when.如果它们的总和低于25,我们总结一些数字,否则返回0.
library("magrittr")
1:3 %>%
purrr::when(sum(.) < 25 ~ sum(.),
~0
)
#> [1] 6
Run Code Online (Sandbox Code Playgroud)
when返回第一个有效条件的操作产生的值.将条件放在左侧~,将操作放在右侧.上面,我们只使用了一个条件(然后是其他情况),但是你可以有很多条件.
您可以轻松地将其集成到更长的管道中.
Cam*_*nek 14
以下是@JohnPaul提供的答案的变体.此变体使用`if`函数而不是复合if ... else ...语句.
library(magrittr)
X <- 1
Y <- TRUE
X %>% `if`(Y, . + 1, .) %>% multiply_by(2)
# [1] 4
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,`if`函数周围不需要花括号,也不需要围绕语句的ifelse函数if ... else ....但是,如果点占位符仅出现在嵌套函数调用中,则默认情况下magrittr将左侧管道输入右侧的第一个参数.通过将表达式括在花括号中来覆盖此行为.注意这两个链之间的区别:
X %>% `if`(Y, . + 1, . + 2)
# [1] TRUE
X %>% {`if`(Y, . + 1, . + 2)}
# [1] 4
Run Code Online (Sandbox Code Playgroud)
点占位符嵌套在函数中调用它出现两次的`if`功能,由于. + 1和. + 2被解释为`+`(., 1)和`+`(., 2)分别.因此,第一个表达式返回结果`if`(1, TRUE, 1 + 1, 1 + 2)(奇怪的是,`if`不会抱怨额外的未使用的参数),第二个表达式返回结果`if`(TRUE, 1 + 1, 1 + 2),这是本例中所需的行为.
有关如何更多信息magrittr管道运营商对待点占位符,请参阅帮助文件的%>%,特别是对"使用点用于其他目的"一节.
Ben*_*ker 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
Run Code Online (Sandbox Code Playgroud)
这是@ 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
Run Code Online (Sandbox Code Playgroud)
我喜欢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
Run Code Online (Sandbox Code Playgroud)
其他例子:
## 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
Run Code Online (Sandbox Code Playgroud)
功能
#' 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
}
}
Run Code Online (Sandbox Code Playgroud)