If a function takes a data frame as the first argument, you can simply add it to the end.
> myFunc <- function(x) sapply(x, max) > mtcars %>% filter(mpg > 20) %>% myFunc() mpg cyl disp hp drat wt qsec vs am gear 33.900 6.000 258.000 113.000 4.930 3.215 22.900 1.000 1.000 5.000 carb 4.000
It should be noted that magrittr::%>% , which is used by dplyr , works with any argument, so you can easily do something like this:
> inc <- function(x) x + 1 > 1 %>% inc(.) %>% sqrt(.) %>% log(.) [1] 0.3465736
and with some useful magrittr magrittr :
library(magrittr) set.seed(1) inTrain <- sample(1:nrow(mtcars), 20) mtcarsTest <- mtcars %>% extract(-inTrain, ) summaryPipe <- function(x) {print(summary(x)); x} mtcars %>% extract(inTrain, ) %>%
This is probably a matter of taste, but personally I find it very useful.
As mentioned in the comments of @BondedDust, there are three possible ways to pass the %>% function. Using the spot placeholder, you can use LHS in a different position than the first (see Calling lm ).
zero323
source share