There are now 3 different R pipes

[This article was first published on R on Tea & Stats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R 4.1.0 has been released and has a couple of handy new features.

One is a shorthand syntax for defining functions. Now, instead of writing, for example

triple <- function(x) x * 3

you can use the more concise syntax

triple <- \(x) x * 3

which may come in handy when using anonymous functions in apply-type calls.

More interesting, though, is the addition of a native pipe operator to R, given by |>, i.e. a pipe and a greater-than sign. As of R 4.1.0, the following are equivalent.

triple(4)
4 |> triple()

This is similar to the functionality previously provided by the magrittr package (often through dplyr and tidyr):

library(magrittr)
4 %>% triple

but saves you loading any add-on packages.

In fact, there already was a pipe of sorts in base R, as John Mount points out: in the form of the ->.; ‘operator’ (assign to a variable called ., then terminate with the rarely-used semicolon):

4 ->.; triple(.)

As a result there are now four different ways of writing the same function call as a one-liner in R version 4.1.0:

triple(4)
4 %>% triple
4 ->.; triple(.)
4 |> triple()

To leave a comment for the author, please follow the link and comment on their blog: R on Tea & Stats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)