Code
library(tidyverse)
data("Hsb82", package = "mlmRev")
Hsb82 <- Hsb82 %>%
group_by(school) %>%
mutate(ses_cm = mean(ses)) %>%
ungroup()magrittrmarklai
December 16, 2020
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
However, it’s kind of embarassing that I only recently found out the assignment pipe (%<>%) operator, as discussed here. For example,
[1] 0.07462564
[1] 1.074626
For the cluster mean example, we can do
# A tibble: 7,185 × 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
# ℹ 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.
---
title: Piping with `magrittr`
author: marklai
date: "2020-12-16"
categories:
- Programming
tags:
- R
---
I have just spent a semester teaching [multilevel modeling](/courses/psyc575), and in the R codes I provided, I usually use the [pipe operator (`%>%`)](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html). For example, to compute the cluster means, we can do
```{r Hsb82, message=FALSE}
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](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html#additional-pipe-operators). For example,
```{r x-pipe, message=FALSE}
library(magrittr)
set.seed(123)
x <- rnorm(10)
mean(x)
# Add 1 to x
x %<>% magrittr::add(1)
mean(x)
# The above is equivalent to
# x <- x + 1
```
For the cluster mean example, we can do
```{r magrittr-assignment}
Hsb82 %<>%
group_by(school) %>%
mutate(ses_cm2 = mean(ses)) %>%
ungroup()
select(Hsb82, ses_cm, ses_cm2)
```
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](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html).