12  管道符-%>%

12.0.1 常见用法

library(tidyverse)

sub<-function(x,y){ #自定义求差函数
  x-y
}

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

12.0.2 指定位置

1 %>% sub(2,.)
[1] 1
1 %>% sub(.,2)
[1] -1
1 %>% 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))