Use pipe without feeding first argument

旧时模样 提交于 2020-01-09 10:18:07

问题


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?

Say I want to specify which variable to use in cor():

library(magrittr)
iris  %>%
  cor(x=.$Sepal.Length, y=.$Sepal.Width)

But this fails, it looks like it call something like cor(., x=.$Sepal.Length, y=.$Sepal.Width) ?

I know I could use instead

iris  %$%
  cor(x=Sepal.Length, y=Sepal.Width)

But wanted to find a solution with %>%...


回答1:


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?

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)}

Or:

iris %$% cor(x = Sepal.Length, y = Sepal.Width)

— after all, that’s what %$% is there for, as opposed to %>%.

But compare:

iris %>% lm(Sepal.Width ~ Sepal.Length, data = .)

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.



来源:https://stackoverflow.com/questions/38717657/use-pipe-without-feeding-first-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!