learn_pipe

管道和数据集参数

Jiaxiang Li 2019-03-12

参考 magrittr vignettes

This operator is handy when functions do not themselves have a data argument, as for example lm and aggregate do.

当 pipeline 传导的参数是 data 时,一般%>%需要%$%替换,见RStudio Community

library(survival)
library(magrittr)
library(tidyverse)
## -- Attaching packages -------------------------------------------------------------------------------- tidyverse 1.2.1 --

## √ ggplot2 3.1.0       √ purrr   0.2.5  
## √ tibble  2.0.1       √ dplyr   0.8.0.1
## √ tidyr   0.8.2       √ stringr 1.3.1  
## √ readr   1.3.1       √ forcats 0.3.0

## -- Conflicts ----------------------------------------------------------------------------------- tidyverse_conflicts() --
## x tidyr::extract()   masks magrittr::extract()
## x dplyr::filter()    masks stats::filter()
## x dplyr::lag()       masks stats::lag()
## x purrr::set_names() masks magrittr::set_names()
data_frame(
        time = c(5,6,3,4,4)
        ,event = c(1,0,0,1,1)
) %$% 
   Surv(time,event)
## Warning: `data_frame()` is deprecated, use `tibble()`.
## This warning is displayed once per session.

## [1] 5  6+ 3+ 4  4

因为Surv不支持 built-in data 参数。

%$% {magrittr} Expose the names in lhs to the rhs expression. This is useful when functions do not have a built-in data argument.

iris %>%
  subset(Sepal.Length > mean(Sepal.Length)) %$%
  cor(Sepal.Length, Sepal.Width)
## [1] 0.3361992
data.frame(z = rnorm(100)) %$% 
  ts.plot(z)

args(cor)
## function (x, y = NULL, use = "everything", method = c("pearson", 
##     "kendall", "spearman")) 
## NULL