当使用管道操作符%>%与包,如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)
没有所有冗余,有没有更好的方法?
鉴于dplyr工作流程:
require(dplyr)
mtcars %>%
tibble::rownames_to_column(var = "model") %>%
filter(grepl(x = model, pattern = "Merc")) %>%
group_by(am) %>%
summarise(meanMPG = mean(mpg))
Run Code Online (Sandbox Code Playgroud)
我有兴趣filter根据价值有条件地申请applyFilter.
对于applyFilter <- 1使用"Merc"字符串过滤行,而不使用过滤器返回所有行.
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))
Run Code Online (Sandbox Code Playgroud)
建议的解决方案效率低,因为ifelse始终会评估调用; 更可取的方法只会评估filter步骤applyFilter <- 1.
在低效的 …