learn_pipe

管道和匿名函数

Jiaxiang Li 2019-03-12

参考 magrittr vignettes

The magrittr (to be pronounced with a sophisticated french accent) is a package with two aims: to decrease development time and to improve readability and maintainability of code. Or even shortr: to make your code smokin’ (puff puff)!

magrittr 是为了减少开发时间(注意不是运行时间),提高可读性和可维护性。

library(magrittr)
mtcars %>%
(function(x) {
  if (nrow(x) > 2) 
    rbind(head(x, 1), tail(x, 1))
  else x
})
##             mpg cyl disp  hp drat   wt  qsec vs am gear carb
## Mazda RX4  21.0   6  160 110 3.90 2.62 16.46  0  1    4    4
## Volvo 142E 21.4   4  121 109 4.11 2.78 18.60  1  1    4    2
mtcars %>%
{ 
  if (nrow(.) > 0)
    rbind(head(., 1), tail(., 1))
  else .
}
##             mpg cyl disp  hp drat   wt  qsec vs am gear carb
## Mazda RX4  21.0   6  160 110 3.90 2.62 16.46  0  1    4    4
## Volvo 142E 21.4   4  121 109 4.11 2.78 18.60  1  1    4    2

注意这里的 code 写法,function(x)if 是实际有意义的函数, {}是没有意义的,所以

这样写

mtcars %>%
{ 
    if (nrow(.) > 0)
        rbind(head(., 1), tail(., 1))
    else .
}
##             mpg cyl disp  hp drat   wt  qsec vs am gear carb
## Mazda RX4  21.0   6  160 110 3.90 2.62 16.46  0  1    4    4
## Volvo 142E 21.4   4  121 109 4.11 2.78 18.60  1  1    4    2

而非

mtcars %>%
    { 
        if (nrow(.) > 0)
            rbind(head(., 1), tail(., 1))
        else .
    }
##             mpg cyl disp  hp drat   wt  qsec vs am gear carb
## Mazda RX4  21.0   6  160 110 3.90 2.62 16.46  0  1    4    4
## Volvo 142E 21.4   4  121 109 4.11 2.78 18.60  1  1    4    2