Steve
Steve

Reputation: 333

R why use <- before pipes

What are the reasons for writing codes like this:

equations <- equations %>%
   some_codes_here

instead of

equations %>%
   some_codes_here

Upvotes: 0

Views: 74

Answers (2)

Yannik Suhre
Yannik Suhre

Reputation: 734

@Arnaud Feldmann is correct. You use the left-directed arrows for assignment. For instance consider the following example:

a <- c(1,2,3)

Now this variable a is saved to your environment. You now can do further things with it. For example you could print it:

print(a)
> 1 2 3

The pipe operator (%>%) you are referring to is an addon from the dplyr or magrittr package. It can be used to chain different operations. Consider following example:

a %>%
  strrep(2)
> "11" "22" "33"

When you combine those both, you can extract and transform different objects (lists, dataframes) with a shorter amount of code. When you combine both techniques it would look like:

b <- a %>%
  strrep(2)

Whereas b now contains the chained command from a.

Upvotes: 1

Arnaud Feldmann
Arnaud Feldmann

Reputation: 765

the basic pipe %>% won't modify the variable before the pipe. There is a different assignment pipe, from the same package magrittr, %<>%, that would also modify the variable equations.

However it is way less common, and most R users consider writing the assignment arrow separately to be a good practice

Upvotes: 1

Related Questions