• Stars
    star
    957
  • Rank 47,767 (Top 1.0 %)
  • Language
    R
  • License
    Other
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Improve the readability of R code with the pipe

magrittr

CRAN status Codecov test coverage R-CMD-check

Overview

The magrittr package offers a set of operators which make your code more readable by:

  • structuring sequences of data operations left-to-right (as opposed to from the inside and out),
  • avoiding nested function calls,
  • minimizing the need for local variables and function definitions, and
  • making it easy to add steps anywhere in the sequence of operations.

The operators pipe their left-hand side values forward into expressions that appear on the right-hand side, i.e.ย one can replace f(x) with x %>% f(), where %>% is the (main) pipe-operator. When coupling several function calls with the pipe-operator, the benefit will become more apparent. Consider this pseudo example:

the_data <-
  read.csv('/path/to/data/file.csv') %>%
  subset(variable_a > x) %>%
  transform(variable_c = variable_a/variable_b) %>%
  head(100)

Four operations are performed to arrive at the desired data set, and they are written in a natural order: the same as the order of execution. Also, no temporary variables are needed. If yet another operation is required, it is straightforward to add to the sequence of operations wherever it may be needed.

If you are new to magrittr, the best place to start is the pipes chapter in R for data science.

Installation

# The easiest way to get magrittr is to install the whole tidyverse:
install.packages("tidyverse")

# Alternatively, install just magrittr:
install.packages("magrittr")

# Or the development version from GitHub:
# install.packages("devtools")
pak::pak("tidyverse/magrittr")

Usage

Basic piping

  • x %>% f is equivalent to f(x)
  • x %>% f(y) is equivalent to f(x, y)
  • x %>% f %>% g %>% h is equivalent to h(g(f(x)))

Here, โ€œequivalentโ€ is not technically exact: evaluation is non-standard, and the left-hand side is evaluated before passed on to the right-hand side expression. However, in most cases this has no practical implication.

The argument placeholder

  • x %>% f(y, .) is equivalent to f(y, x)
  • x %>% f(y, z = .) is equivalent to f(y, z = x)

Re-using the placeholder for attributes

It is straightforward to use the placeholder several times in a right-hand side expression. However, when the placeholder only appears in a nested expressions magrittr will still apply the first-argument rule. The reason is that in most cases this results more clean code.

x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))

The behavior can be overruled by enclosing the right-hand side in braces:

x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))

Building (unary) functions

Any pipeline starting with the . will return a function which can later be used to apply the pipeline to values. Building functions in magrittr is therefore similar to building other values.

f <- . %>% cos %>% sin 
# is equivalent to 
f <- function(.) sin(cos(.)) 

Pipe with exposition of variables

Many functions accept a data argument, e.g.ย lm and aggregate, which is very useful in a pipeline where data is first processed and then passed into such a function. There are also functions that do not have a data argument, for which it is useful to expose the variables in the data. This is done with the %$% operator:

iris %>%
  subset(Sepal.Length > mean(Sepal.Length)) %$%
  cor(Sepal.Length, Sepal.Width)
#> [1] 0.3361992

data.frame(z = rnorm(100)) %$%
  ts.plot(z)

Code of Conduct

Please note that the magrittr project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

More Repositories

1

ggplot2

An implementation of the Grammar of Graphics in R
R
6,496
star
2

dplyr

dplyr: A grammar of data manipulation
R
4,725
star
3

tidyverse

Easily install and load packages from the tidyverse
R
1,633
star
4

rvest

Simple web scraping for R
R
1,488
star
5

tidyr

Tidy Messy Data
R
1,369
star
6

purrr

A functional programming toolkit for R
R
1,254
star
7

readr

Read flat files (csv, tsv, fwf) into R
R
1,001
star
8

datascience-box

Data Science Course in a Box
JavaScript
937
star
9

reprex

Render bits of R code for sharing, e.g., on GitHub or StackOverflow.
R
735
star
10

lubridate

Make working with dates in R just that little bit easier
R
727
star
11

readxl

Read excel files (.xls and .xlsx) into R ๐Ÿ–‡
C++
726
star
12

glue

Glue strings to data in R. Small, fast, dependency free interpreted string literals.
R
705
star
13

dtplyr

Data table backend for dplyr
R
661
star
14

tibble

A modern re-imagining of the data frame
R
659
star
15

multidplyr

A dplyr backend that partitions a data frame over multiple processes
R
640
star
16

vroom

Fast reading of delimited files
C++
618
star
17

stringr

A fresh approach to string manipulation in R
R
594
star
18

forcats

๐Ÿˆ๐Ÿˆ๐Ÿˆ๐Ÿˆ: tools for working with categorical variables (factors)
R
551
star
19

dbplyr

Database (DBI) backend for dplyr
R
473
star
20

haven

Read SPSS, Stata and SAS files from R
C
423
star
21

modelr

Helper functions for modelling
R
401
star
22

googlesheets4

Google Spreadsheets R API (reboot of the googlesheets package)
R
354
star
23

googledrive

Google Drive R API
R
321
star
24

style

The tidyverse style guide for R code
HTML
291
star
25

duckplyr

A drop-in replacement for dplyr, powered by DuckDB for performance.
R
236
star
26

design

Tidyverse design principles
R
217
star
27

tidyverse.org

Source of tidyverse.org
HTML
191
star
28

hms

A simple class for storing time-of-day values
R
137
star
29

nycflights13

An R data package containing all out-bound flights from NYC in 2013 + useful metdata
R
127
star
30

tidyversedashboard

Tidyverse activity dashboard
R
71
star
31

tidy-dev-day

Tidyverse developer day
R
69
star
32

tidyeval

A guide to tidy evaluation
CSS
55
star
33

dsbox

Companion R package to Data Science Course in a Box
R
49
star
34

tidytemplate

A pkgdown template for core tidyverse packages
SCSS
45
star
35

blob

A simple S3 class for representing BLOBs
R
44
star
36

funs

Collection of low-level functions for working with vctrs
R
34
star
37

code-review

33
star
38

website-analytics

Web analytics for tidyverse + r-lib sites
R
28
star
39

tidyups

21
star
40

ggplot2-docs

ggplot2 documentation. Auto-generated from ggplot2 sources by pkgdown
HTML
10
star