R 使用管道运算符时的条件评估 %>% [英] R Conditional evaluation when using the pipe operator %>%
问题描述
当使用管道运算符 %>%
和 dplyr
、ggvis
、dycharts
等包时,等等,我如何有条件地做一个步骤?例如;
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
中,如果Y
为TRUE
则加1,否则只返回X的最后一个值代码>.
.
是一个替身,它告诉函数链上一步的输出去哪里,所以我可以在两个分支上使用它.
编辑正如@BenBolker 指出的那样,您可能不想要 ifelse
,所以这里有一个 if
版本.
X %>%添加(1)%>%{if(Y) add(.,1) else .}
感谢@Frank 指出我应该在我的 if
和 ifelse
语句周围使用 {
大括号来继续链.>
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 使用管道运算符时的条件评估 %>%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!