R 使用管道运算符时的条件评估 %>% [英] R Conditional evaluation when using the pipe operator %>%

查看:20
本文介绍了R 使用管道运算符时的条件评估 %>%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用管道运算符 %>%dplyrggvisdycharts 等包时,等等,我如何有条件地做一个步骤?例如;

step_1 %>%步骤_2%>%如果(条件)step_3

这些方法似乎不起作用:

step_1 %>%第2步如果(条件)%>% step_3步骤_1 %>%步骤_2%>%如果(条件)step_3

还有很长的路要走:

if(条件){步骤_1 %>%第2步}别的{步骤_1 %>%步骤_2%>%step_3}

有没有更好的方法没有所有的冗余?

解决方案

这是一个利用 .ifelse 的快速示例:

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

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

编辑正如@BenBolker 指出的那样,您可能不想要 ifelse,所以这里有一个 if 版本.

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

感谢@Frank 指出我应该在我的 ififelse 语句周围使用 { 大括号来继续链.>

When using the pipe operator %>% with packages such as dplyr, ggvis, dycharts, etc, how do I do a step conditionally? For example;

step_1 %>%
step_2 %>%

if(condition)
step_3

These approaches don't seem to work:

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

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

There is a long way:

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

Is there a better way without all the redundancy?

解决方案

Here is a quick example that takes advantage of the . and ifelse:

X<-1
Y<-T

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

In the ifelse, if Y is TRUE if will add 1, otherwise it will just return the last value of X. The . is a stand-in which tells the function where the output from the previous step of the chain goes, so I can use it on both branches.

Edit As @BenBolker pointed out, you might not want ifelse, so here is an if version.

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

Thanks to @Frank for pointing out that I should use { braces around my if and ifelse statements to continue the chain.

这篇关于R 使用管道运算符时的条件评估 %&gt;%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆