22

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

zx8754
  • 52,746
  • 12
  • 114
  • 209
Matifou
  • 7,968
  • 3
  • 47
  • 52

3 Answers3

29

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Great! I was missing the brace, thanks for the explanation! and sorry for the typo mentioning initially %$% when I meant %>% ! – Matifou Aug 02 '16 at 10:24
2

One can use an anonymous function

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

# [1] -0.1175698
Julien
  • 1,613
  • 1
  • 10
  • 26
0

please check pipeR package. This packages defines %>>% operator so that you can inpute your lhs object as . argument in the rhs function.

For example, suppose lst is a list of matrix, and you want to cbind all of them. You can do this: lst %>>% {do.call(cbind, .)}

Santos
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 03 '23 at 05:25