Use the new R pipe built into R 4.1

The R language has a new, built-in pipe operator as of R version 4.1:  |> 

%>% is the pipe that most R users know. Originally from the magrittr package, it’s now used in many other packages as well. (If you’re wondering where the magrittr name came from, it’s a reference to Belgian artist Rene Magritte and one of his paintings, The Treachery of Images, that says in French: “This is not a pipe.”)

Here’s a somewhat trivial example using the %>% pipe with the mtcars data set and a couple of dplyr functions. This code filters the data for rows with more than 25 mpg and arranges the results by descending miles per gallon:

mtcars %>%
filter(mpg > 25) %>%

Not everyone likes the pipe syntax. But especially when using tidyverse functions, there are advantages in code readability, in not having to repeat the data frame name, and not creating new copies of a data set. Here are some non-pipe ways of writing the same dplyr code:

mtcars <- filter(mtcars, mpg > 25)
mtcars <- arrange(mtcars, desc(mpg))

# OR

arrange(filter(mtcars, mpg > 25), desc(mpg))

Run R 4.1 in Docker

If you’re not yet ready to install R 4.1 on your system, one easy way to try out the new pipe is by running R 4.1 inside a Docker container. I provide full general instructions in “How to run R 4.0 in Docker” — the only new part is using a Docker image with R 4.1. Basically, you need to download and install Docker if you don’t already have it, launch Docker, and then run the code below in a terminal window (not the R console). 

docker run -e PASSWORD=your_password_here --rm -p 8787:8787 -v /path/to/local/directory:/home/rstudio/morewithr rocker/tidyverse:4.1.0

The -v /path/to/local/directory:/home/rstudio/morewithr part of the code creates a volume connecting a directory inside the Docker container to files in a local directory. That’s optional but can be quite handy.

Copyright © 2021 IDG Communications, Inc.

Source link