1.13 Using pipes

  • Tidyverse packages like dplyr and tidyr allow you to write code using the pipe %>% operator.

  • The %>% operator passes the result on the left to the first parameter of the function on the right.

library(dplyr)

# calculate the mean height for women by species
newdata <- starwars %>%
  filter(gender == "feminine") %>%
  group_by(species) %>%
  summarize(mean_ht = mean(height, na.rm = TRUE))

newdata
## # A tibble: 8 × 2
##   species    mean_ht
##   <chr>        <dbl>
## 1 Clawdite      168 
## 2 Droid          96 
## 3 Human         164.
## 4 Kaminoan      213 
## 5 Mirialan      168 
## 6 Tholothian    184 
## 7 Togruta       178 
## 8 Twi'lek       178