Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 248

7.3.2 Piping with R

Оглавление

This section is not about creating beautiful music, it explains an argument passing system in R. Similar to the pipe in Linux, the pipe operator, |, the operator %>% from the package magrittr allows to pass the output of one line to the first argument of the function on the next line.11

pipe

magrittr

% > %

When writing code, it is common to work on one object for a while. For example, when we need to import data, then work with that data to clean it, add columns, delete some, summarize data, etc.

To start, consider a simple example:

t <- tibble(“x” = runif(10)) t <- within(t, y <- 2 * x + 4 + rnorm(10, mean=0,sd=0.5))

This can also be written with the piping operator from magrittr

t <- tibble(“x” = runif(10)) %>% within(y <- 2 * x + 4 + rnorm(10, mean=0,sd=0.5))

What R does behind the scenes, is feeding the output left of the pipe operator as main input right of the pipe operator. This means that the following are equivalent:

# 1. pipe: a %>% f() # 2. pipe with shortened function: a %>% f # 3. is equivalent with: f(a)

The Big R-Book

Подняться наверх