R使用管道运算符时的条件评估%>% [英] R Conditional evaluation when using the pipe operator %>%
问题描述
当使用管道操作符%>%
与软件包 dplyr
, ggvis
, dycharts
等,我如何有条件地做一个步骤?例如;
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
有很长的路要走:
if(condition)
{
step_1 %>%
step_2
}else{
step_1 %>%
step_2 %>%
step_3
}
有没有一个更好的方法没有所有的冗余?
Is there a better way without all the redundancy? I am working with dygraphs
for now if that matters.
推荐答案
这里我正在使用 dygraphs
是一个利用的快速示例。
和ifelse;
Here is a quick example that take advantage of the .
and ifelse;
X<-1
Y<-T
X %>% add(1) %>% { ifelse(Y ,add(1), . ) }
在 ifelse
如果 / code>是
TRUE
如果将添加1,否则它将返回最后一个值 X
。 。
是一个备用,它告诉函数上一步链接输出的位置,所以我可以在两个分支上使用它。
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.
修改
由于@BenBolker指出,您可能不想要 ifelse
,所以这里是一个如果
版本。
Edit
As @BenBolker pointed out, you might not want ifelse
, so here is a if
version.
X %>%
add(1) %>%
{if(Y) add(1) else .}
感谢@Frank指出,我应该使用 {
大括号围绕我的如果
和 ifelse
语句来继续链接。
Thanks to @Frank for pointing out that I should use {
braces around my if
and ifelse
statements to continue the chain.
这篇关于R使用管道运算符时的条件评估%>%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!