I want to use qplot
(ggplot2) and then forward the data with magrittr
:
This works:
mtcars %>% qplot(mpg, cyl, data=.)
This produces an error:
mtcars %>% qplot(mpg, cyl, data=.) %>% summarise(mean(mpg))
And those produce only summary statistics:
mtcars %T>% qplot(mpg, cyl, data=.) %>% summarise(mean(mpg))
mtcars %>% {qplot(mpg, cyl, data=.); .} %>% summarise(mean(mpg))
mtcars %T>% {qplot(mpg, cyl, data=.)} %>% summarise(mean(mpg))
What is the problem? I already found this solution, but it does not help, as you see from the code attached.
All ggplot2 functions return an object that represents a plot - to see it you need to print it. That normally happens automatically when you're working in the console, but needs to explicit inside a function or a chain.
The most elegant solution I could come up with is this:
library("ggplot2")
library("magrittr")
library("dplyr")
echo <- function(x) {
print(x)
x
}
mtcars %>%
{echo(qplot(mpg, cyl, data = .))} %>%
summarise(mean(mpg))
It seems like there should be a better way.