用...公开内容

展示管道运算符%$%将列名称作为左侧对象内的 R 符号暴露给右侧表达式。当管道输入没有 data 参数的函数(比如 lm)并且不将 data.frame 和列名称作为参数(大多数主要的 dplyr 函数)时,这个运算符很方便。

展示管道运算符%$%允许用户在需要引用列名时避免破坏管道。例如,假设你要过滤 data.frame,然后使用 cor.test 在两列上运行相关性测试:

library(magrittr)
library(dplyr)
mtcars %>%
  filter(wt > 2) %$%
  cor.test(hp, mpg)

#> 
#>  Pearson's product-moment correlation
#> 
#> data:  hp and mpg
#> t = -5.9546, df = 26, p-value = 2.768e-06
#> alternative hypothesis: true correlation is not equal to 0
#> 95 percent confidence interval:
#>  -0.8825498 -0.5393217
#> sample estimates:
#>        cor 
#> -0.7595673

这里标准的%>%管道将 data.frame 传递给 filter(),而%$%管道将列名称暴露给 cor.test()

展示管的工作方式类似于基本 R with() 函数的可管道版本,并且接受相同的左侧对象作为输入。