我试图找出当我将数据传递给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不知道如何处理类protoenvironment的数据”。
mtcars %T>%
ggplot() + geom_point(aes(cyl, mpg)) %>%
ggplot() + geom_point(aes(mpg, cyl))
任何人都可以解释为什么最后一段代码不起作用吗?
答案 0 :(得分:6)
我认为你的问题与操作顺序有关。 +
强于%T>%
运算符(根据?Syntax
帮助页面)。在添加ggplot
之前,您需要将data =参数传递给geom_point
,否则会让事情变得混乱。我想你想要
mtcars %T>%
{print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>%
{ggplot(.) + geom_point(aes(mpg, cyl))}
使用功能性"短手"符号
答案 1 :(得分:6)
要么
mtcars %T>%
{print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>%
{ggplot(.) + geom_point(aes(mpg, cyl))}
或放弃%T>%
运算符并使用带有"%> T%"的普通管道。操作明确表示为suggested in this answer
techo <- function(x){
print(x)
x
}
mtcars %>%
{techo( ggplot(.) + geom_point(aes(cyl, mpg)) )} %>%
{ggplot(.) + geom_point(aes(mpg, cyl))}
正如TFlick所指出的,%T&gt;%运算符在此处不起作用的原因是因为操作的优先级:%any%
在+
之前完成。
答案 2 :(得分: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))}