Piping with `magrittr`

I have just spent a semester teaching multilevel modeling, and in the R codes I provided, I usually use the pipe operator (%>%). For example, to compute the cluster means, we can do

library(tidyverse)
data("Hsb82", package = "mlmRev")
Hsb82 <- Hsb82 %>% 
  group_by(school) %>% 
  mutate(ses_cm = mean(ses)) %>% 
  ungroup()

However, it’s kind of embarassing that I only recently found out the assignment pipe (%<>%) operator, as discussed here. For example,

library(magrittr)
set.seed(123)
x <- rnorm(10)
mean(x)
## [1] 0.07462564
# Add 1 to x
x %<>% magrittr::add(1)
mean(x)
## [1] 1.074626
# The above is equivalent to 
# x <- x + 1

For the cluster mean example, we can do

Hsb82 %<>% 
  group_by(school) %>% 
  mutate(ses_cm2 = mean(ses)) %>% 
  ungroup()
select(Hsb82, ses_cm, ses_cm2)
## # A tibble: 7,185 x 2
##    ses_cm ses_cm2
##     <dbl>   <dbl>
##  1 -0.434  -0.434
##  2 -0.434  -0.434
##  3 -0.434  -0.434
##  4 -0.434  -0.434
##  5 -0.434  -0.434
##  6 -0.434  -0.434
##  7 -0.434  -0.434
##  8 -0.434  -0.434
##  9 -0.434  -0.434
## 10 -0.434  -0.434
## # … with 7,175 more rows

which saves the additional typing of Hsb82 <- Hsb82 %>%. That said, the %<>% is not commonly seen when reading other people’s code, so perhaps the R community still prefer just using the %>% operator. But it’s at least good to know there is a potentially more convenient way. There is also the %$% and %T>% operator, as discussed in this vignette.

Yuan Bo 袁博
Yuan Bo 袁博
Associate Professor of Psychology (Social Psychology)

My research examines the nature and dynamics of social norms, namely how norms may emerge and become stable, why norms may suddenly change, how is it possible that inefficient or unpopular norms survive, and what motivates people to obey norms. I combines laboratory and simulation experiments to test theoretical predictions and build empirically-grounded models of social norms and their dynamics.

comments powered by Disqus

Related