chain {dplyr} | R Documentation

## Chain together multiple operations.

### Description

The downside of the functional nature of dplyr is that when you combine multiple data manipulation operations, you have to read from the inside out and the arguments may be very distant to the function call. These functions providing an alternative way of calling dplyr (and other data manipulation) functions that you read can from left to right.

### Usage

    chain(..., env = parent.frame())

    chain_q(calls, env = parent.frame())

    lhs %.% rhs

    lhs %>% rhs

### Arguments

`...,calls` | A sequence of data transformations, starting with a dataset. The first argument of each call should be omitted - the value of the previous step will be substituted in automatically. Use `chain` and `...` when working interactive; use `chain_q` and `calls` when calling from another function.
`env` | Environment in which to evaluation expressions. In ordinary operation you should not need to set this parameter.
`lhs,rhs` | A dataset and function to apply to it

### Details

The functions work via simple substitution so that `x %>% f(y)` is translated into `f(x, y)`.

### Deprecation

`chain` was deprecated in version 0.2, and will be removed in 0.3. `%.%` was deprecated in version 0.3, and defunct in 0.4. They wwere removed in the interest of making dplyr code more standardised and `%>%` is much more popular.

### See Also

`%>%` in the magrittr package for a more detailed explanation of the forward pipe semantics.

### Examples

    # If you're performing many operations you can either do step by step
    if (require("nycflights13")) {
    a1 <- group_by(flights, year, month, day)
    a2 <- select(a1, arr_delay, dep_delay)
    a3 <- summarise(a2,
      arr = mean(arr_delay, na.rm = TRUE),
      dep = mean(dep_delay, na.rm = TRUE))
    a4 <- filter(a3, arr > 30 | dep > 30)

    # If you don't want to save the intermediate results, you need to
    # wrap the functions:
    filter(
      summarise(
        select(
          group_by(flights, year, month, day),
          arr_delay, dep_delay
        ),
        arr = mean(arr_delay, na.rm = TRUE),
        dep = mean(dep_delay, na.rm = TRUE)
      ),
      arr > 30 | dep > 30
    )

    # This is difficult to read because the order of the operations is from
    # inside to out, and the arguments are a long way away from the function.
    # Alternatively you can use %>% to sequence the operations
    # linearly:

    flights %>%
      group_by(year, month, day) %>%
      select(arr_delay, dep_delay) %>%
      summarise(
        arr = mean(arr_delay, na.rm = TRUE),
        dep = mean(dep_delay, na.rm = TRUE)
      ) %>%
      filter(arr > 30 | dep > 30)
    }

[Package dplyr version 0.4.3 Index]