Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pipe without feeding first argument

Tags:

r

pipe

magrittr

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

like image 925
Matifou Avatar asked Aug 02 '16 10:08

Matifou


People also ask

Can you use pipe in a function in R?

The pipe operator, written as %>% , has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps.

What does %$% do in R?

The exposition ( %$% ) operator is useful when you want to pipe a dataframe, which may contain many columns, into a function that is only applied to some of the columns.

What does it mean to pipe a function?

The command line programs that do the further processing are referred to as filters. We can define pipe function: A pipe function is a function that accepts a series of functions, which process an input parameter and return a output which will be the input for the next function.

What are pipes in R?

The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.


1 Answers

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.

like image 64
Konrad Rudolph Avatar answered Jan 02 '23 04:01

Konrad Rudolph