10

我试图弄清楚为什么当我将数据传递给 ggplot 命令时 tee 运算符 %T>% 不起作用。

这工作正常

library(ggplot2)
library(dplyr)
library(magrittr)

mtcars %T>%
  qplot(x = cyl, y = mpg, data = ., geom = "point") %>%
  qplot(x = mpg, y = cyl, data = ., geom = "point")

这也很好用

mtcars %>%
  {ggplot() + geom_point(aes(cyl, mpg)) ; . } %>%
  ggplot() + geom_point(aes(mpg, cyl))

但是当我使用 tee 运算符时,如下所示,它会抛出“错误:ggplot2 不知道如何处理类原型环境的数据”。

mtcars %T>%
  ggplot() + geom_point(aes(cyl, mpg)) %>%
  ggplot() + geom_point(aes(mpg, cyl))

谁能解释为什么最后一段代码不起作用?

4

3 回答 3

11

任何一个

mtcars %T>%
  {print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>%
  {ggplot(.) + geom_point(aes(mpg, cyl))}

或放弃%T>%运营商并使用普通管道,将“%>T%”操作明确为this answer中建议的新功能

techo <- function(x){
    print(x)
    x
  }

mtcars %>%
  {techo( ggplot(.) + geom_point(aes(cyl, mpg)) )} %>%
  {ggplot(.) + geom_point(aes(mpg, cyl))}

正如 TFlick 所指出的, %T>% 运算符在这里不起作用的原因是操作的优先级:%any%is done before +

于 2014-12-08T00:36:00.587 回答
6

我认为您的问题与操作顺序有关。+%T>%运算符强(根据帮助?Syntax页面)。ggplot在添加之前,您需要传入 data= 参数,geom_point否则事情会变得一团糟。我想你想要

mtcars %T>%
  {print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>%
  {ggplot(.) + geom_point(aes(mpg, cyl))}

它使用功能性“速记”符号

于 2014-12-03T05:45:49.023 回答
0

请注意,返回的 ggplot 对象是带有 $data 字段的列表。可以利用这一点。个人觉得风格比较干净:)

ggpass=function(pp){
print(pp)
return(pp$data)
}
mtcars %>%
  {ggplot() + geom_point(aes(cyl, mpg))} %>% ggpass() %>%
  {ggplot() + geom_point(aes(mpg, cyl))}
于 2018-01-06T01:06:39.327 回答