Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

r - Use pipe without feeding first argument

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 %>%...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...