Different Pipe Operators in R

The Exposition Pipe %$%

The exposition pipe (%$%), also from the magrittr package, behaves slightly differently. Instead of passing a dataset as an argument, it exposes the variable names of a data frame directly to the next function.

For example, we can write:

bfi %$% lm(extra ~ age)

Call:
lm(formula = extra ~ age)

Coefficients:
(Intercept)          age  
    3.97269      0.00599  

This works because %$% allows the variables extra and age to be used as if they were objects in the global environment, even though they come from within bfi. In practice this means that what we just did is equivalent to:

lm(bfi$extra ~ bfi$age)

Call:
lm(formula = bfi$extra ~ bfi$age)

Coefficients:
(Intercept)      bfi$age  
    3.97269      0.00599  

The Base R Pipe |>

As of R 4.1, there’s also a native pipe operator: |>. It works like %>% but is simpler and doesn’t require loading dplyr or magrittr.

You can re-create the first example using only base R syntax:

bfi[c("agree", "consc", "extra", "neuro", "open")] |>
  cov(use = "pairwise") |>
  diag() |>
  sqrt()
    agree     consc     extra     neuro      open 
0.8984019 0.9513469 1.0609041 1.1963314 0.8083739 

The base pipe is great for lightweight pipelines, while the %>% pipe remains preferred for more complex workflows, especially those using tidyverse functions like mutate(), filter(), and select().

Practice

Use the pipe and exposition pipe to calculate the correlation between age and agree for adults in the bfi data.

You can use the cor() function to compute the correlation between two variables.

bfi %>%
  filter(age >= 18) %$%
  cor(age, agree)
[1] 0.1546906
Back to top