library(tidyverse)
data("Hsb82", package = "mlmRev")
Hsb82 <- Hsb82 %>%
group_by(school) %>%
mutate(ses_cm = mean(ses)) %>%
ungroup()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
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 + 1For 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 × 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.