鉴于 dplyr 工作流程:
require(dplyr)
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
filter(grepl(x = model, pattern = "Merc")) %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
我有兴趣有条件申请filter
取决于的值applyFilter
.
Solution
For applyFilter <- 1
使用以下内容过滤行"Merc"
字符串,不带过滤器all返回行。
applyFilter <- 1
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
filter(model %in%
if (applyFilter) {
rownames(mtcars)[grepl(x = rownames(mtcars), pattern = "Merc")]
} else
{
rownames(mtcars)
}) %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
Problem
建议的解决方案效率低下,因为ifelse
调用总是被评估;更理想的方法只会评估filter
迈出一步applyFilter <- 1
.
Attempt
The 效率低下工作解决方案如下所示:
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
# Only apply filter step if condition is met
if (applyFilter) {
filter(grepl(x = model, pattern = "Merc"))
}
%>%
# Continue
group_by(am) %>%
summarise(meanMPG = mean(mpg))
当然,上面的语法是不正确的。这只是理想工作流程的示例。
想要的答案
这种方法怎么样:
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
filter(if(applyfilter== 1) grepl(x = model, pattern = "Merc") else TRUE) %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
这意味着grepl
仅当 applyfilter 为 1 时才进行评估,否则filter
只是回收一个TRUE
.
或者另一种选择是使用{}
:
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
{if(applyfilter == 1) filter(., grepl(x = model, pattern = "Merc")) else .} %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
显然还有另一种可能的方法,您可以简单地破坏管道,有条件地执行过滤器,然后继续管道(我知道OP没有要求这样做,只是想为其他读者提供另一个例子)
mtcars %<>%
tibble::rownames_to_column(var = "model")
if(applyfilter == 1) mtcars %<>% filter(grepl(x = model, pattern = "Merc"))
mtcars %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)