12  管道符

12.0.1 常见用法

library(tidyverse)
my_sub<-function(x,y){
  x-y
}

my_sub(1,2)
[1] -1
my_sub(2,3)
[1] -1
#借用管道符调用
1 %>% my_sub(2)
[1] -1
2 %>% my_sub(3)
[1] -1
#连续调用
3 %>% my_sub(1) %>% my_sub(2)
[1] 0
mean(1:10)
[1] 5.5
1:10 %>% mean() %>% class()
[1] "numeric"

12.0.2 指定位置

1 %>% my_sub(2,.)
[1] 1
1 %>% my_sub(.,2)
[1] -1
1 %>% my_sub(.,.)
[1] 0
mean(c(1:10,NA))
[1] NA
mean(c(1:10,NA),na.rm=TRUE)
[1] 5.5
TRUE %>% mean(c(1:10,NA),na.rm=.)
[1] 5.5

12.0.3 实战应用

管道符的优势即是连续调用

mtcars %>%
  filter(cyl==4) %>%
  mutate(mpg2=mpg+100) %>%
  select(cyl,mpg,mpg2) %>%
  head()

等价于

head(select(mutate(filter(mtcars,cyl==4),mpg2=mpg+100),cyl,mpg,mpg2))