使用管道时无需输入第一个参数 [英] Use pipe without feeding first argument
问题描述
%>%
管道运算符是否总是将左侧(LHS)馈入右侧(RHS)的第一个自变量?即使在RHS调用中再次指定了第一个参数?
Is the %>%
pipe operator always feeding the left-hand side (LHS) to the first argument of the right-hand side (RHS)? Even if the first argument is specified again in the RHS call?
说我想指定在cor()
中使用哪个变量:
Say I want to specify which variable to use in cor()
:
library(magrittr)
iris %>%
cor(x=.$Sepal.Length, y=.$Sepal.Width)
但是这失败了,看起来像是调用了cor(., x=.$Sepal.Length, y=.$Sepal.Width)
之类的东西?
But this fails, it looks like it call something like cor(., x=.$Sepal.Length, y=.$Sepal.Width)
?
我知道我可以代替
iris %$%
cor(x=Sepal.Length, y=Sepal.Width)
但想用%>%
...
推荐答案
%>%
管道运算符是否总是将左侧(LHS)馈入右侧(RHS)的第一个自变量?即使在RHS调用中再次指定了第一个参数?
Is the
%>%
pipe operator always feeding the left-hand side (LHS) to the first argument of the right-hand side (RHS)? Even if the first argument is specified again in the RHS call?
不.您自己已经注意到了该异常:如果右侧使用.
,则左侧的第一个参数是 not 输入的.您需要手动传递它.
No. You’ve noticed the exception yourself: if the right-hand side uses .
, the first argument of the left-hand side is not fed in. You need to pass it manually.
但是,由于您不是单独使用.
而是在表达式中使用它,因此在您的情况下不会发生 .为了避免将左侧作为第一个参数,您还需要使用花括号:
However, this is not happening in your case because you’re not using .
by itself, you’re using it inside an expression. To avoid the left-hand side being fed as the first argument, you additionally need to use braces:
iris %>% {cor(x = .$Sepal.Length, y = .$Sepal.Width)}
或者:
iris %$% cor(x = Sepal.Length, y = Sepal.Width)
-毕竟,这就是%$%
的用途,而不是%>%
.
— after all, that’s what %$%
is there for, as opposed to %>%
.
但是比较一下:
iris %>% lm(Sepal.Width ~ Sepal.Length, data = .)
在这里,我们将左侧表达式显式传递为lm
的data
参数.这样,我们可以防止将它作为第一个参数传递给lm
.
Here, we’re passing the left-hand side expression explicitly as the data
argument to lm
. By doing so, we prevent it being passed as the first argument to lm
.
这篇关于使用管道时无需输入第一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!