Dplyr + magrittr + qplot = no graph?

I want to use qplot (ggplot2) and then forward the data using magrittr :

It works:

 mtcars %>% qplot(mpg, cyl, data=.) 

This causes an error:

 mtcars %>% qplot(mpg, cyl, data=.) %>% summarise(mean(mpg)) 

And they only produce 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 can be seen from the attached code.

+4
r ggplot2 dplyr magrittr
source share
2 answers

All ggplot2 functions return an object that represents the graph - to see it, to print it. This usually happens automatically when you work in the console, but you need to explicitly specify it inside the function or chain.

The most elegant solution I could come up with is the following:

 library("ggplot2") library("magrittr") library("dplyr") echo <- function(x) { print(x) x } mtcars %>% {echo(qplot(mpg, cyl, data = .))} %>% summarise(mean(mpg)) 

There seems to be a better way.

+5
source share

This seems cleaner to me because it does not need to use %T>% (which IMHO makes it easy to reinstall and read the channel) and {} around the expression to avoid passing the object there. I am not sure how much harm there is in transferring an object and ignoring it.

I never used the %T>% tag, where I also did not want to print or draw. And I never wanted to print / build an object that is being broadcast (usually this is a large data set). Therefore, I never use %T>% .

 library("ggplot2") library("dplyr") pap = function(pass, to_print = NULL, side_effect = NULL) { if( !is.null(to_print)) { if (is.function(to_print)) { print(to_print(pass)) } else { print(to_print) } } side_effect invisible(pass) } mtcars %>% pap(summary) %>% pap(side_effect = plot(.)) %>% pap(qplot(mpg, cyl, data = .)) %>% summarise(mean(mpg)) 

I usually don’t use build as a side effect in my pipes, so the solution above works best for me (for the “side effect”, an “extra setup” is required). I would like to be able to unambiguously sort these scenarios (for example, a graph against qplot), but I did not find a reliable way.

+2
source share

All Articles