library(tidyverse)
<-function(x,y){ #自定义求差函数
sub-y
x
}
sub(1,2)
[1] -1
sub(2,3)
[1] -1
library(tidyverse)
<-function(x,y){ #自定义求差函数
sub-y
x
}
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"
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
管道符的优势即是连续调用
%>%
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))