Skip to content
Prev 393508 / 398506 Next

Pipe operator

Christopher Ryan sent this example
c(1:10) %>% sqrt() %>% mean() %>% plot()
I could code this as

A <- c(1:10)
B <- sqrt(A)
C<- mean(B)
plot(C)

I can then clean up by removing variables that I have no further use for.
rm(A, B, C)

The %>% operator is from the magriter package. It can be installed directly, or it is also installed if you use the tidyverse package (and possibly many others). The |> is base R, but it was added in R version 4.1.0.

I do not know if it increases processing speed.
It can save memory usage, especially if one is a messy programmer and does not tidy up after each task.
If you wanted to test execution times for bits of code there is the microbenchmark package.

Tim

-----Original Message-----
From: Sorkin, John <jsorkin at som.umaryland.edu> 
Sent: Tuesday, January 3, 2023 12:13 PM
To: Ebert,Timothy Aaron <tebert at ufl.edu>; 'R-help Mailing List' <r-help at r-project.org>
Subject: Re: Pipe operator

[External Email]

Tim,

Thank you for your reply. I did not know about the |> operator. Do both %>% and |> work in base R?

You suggested that the pipe operator can produce code with fewer variables. May I ask you to send a short example in which the pipe operator saves variables. Does said saving of variables speed up processing or result in less memory usage?

Thank you,
John
Message-ID: <BN6PR2201MB155378D68586F7781F2EEA60CFF49@BN6PR2201MB1553.namprd22.prod.outlook.com>
In-Reply-To: <MW4PR03MB63630F7F3EA776AB218EFD2AE2F49@MW4PR03MB6363.namprd03.prod.outlook.com>