I am trying to figure out why the tee operator, %T>%, does not work when I pass the data to a ggplot command.
This works fine
library(ggplot2)
library(dplyr)
library(magrittr)
mtcars %T>%
qplot(x = cyl, y = mpg, data = ., geom = "point") %>%
qplot(x = mpg, y = cyl, data = ., geom = "point")
And this also works fine
mtcars %>%
{ggplot() + geom_point(aes(cyl, mpg)) ; . } %>%
ggplot() + geom_point(aes(mpg, cyl))
But when I use the tee operator, as below, it throws "Error: ggplot2 doesn't know how to deal with data of class protoenvironment".
mtcars %T>%
ggplot() + geom_point(aes(cyl, mpg)) %>%
ggplot() + geom_point(aes(mpg, cyl))
Can anyone explain why this final piece of code does not work?
Integrating the pipe operator with ggplot2 We can also use the pipe operator to pass the data argument to the ggplot() function. The hard part is to remember that to build your ggplot, you need to use + and not %>% . The pipe operator can also be used to link data manipulation with consequent data visualization.
%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.
%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.
The magrittr pipe operators use non-standard evaluation. They capture their inputs and examines them to figure out how to proceed. First a function is produced from all of the individual right-hand side expressions, and then the result is obtained by applying this function to the left-hand side.
Either
mtcars %T>%
{print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>%
{ggplot(.) + geom_point(aes(mpg, cyl))}
or abandon the %T>%
operator and use an ordinary pipe with the "%>T%" operation made explicit as a new function as suggested in this answer
techo <- function(x){
print(x)
x
}
mtcars %>%
{techo( ggplot(.) + geom_point(aes(cyl, mpg)) )} %>%
{ggplot(.) + geom_point(aes(mpg, cyl))}
As TFlick noted, the reason the %T>% operator doesn't work here is because of the precedence of operations: %any%
is done before +
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With