Home > Enterprise >  How to use the %T>% pipe after ggplot?
How to use the %T>% pipe after ggplot?

Time:07-01

Let's take a look at the following two pieces of code:

mtcars %>%
    ggplot(aes(x = cyl, y = mpg)) 
    geom_line()

This works and creates the following plot:

enter image description here

Now let's look at this:

mtcars %>%
    group_by(cyl) %>% 
    summarise(mpg = mean(mpg))

This also works and creates the following output:

# A tibble: 3 x 2
    cyl   mpg
  <dbl> <dbl>
1     4  26.7
2     6  19.7
3     8  15.1

However, this doesn't work:

mtcars %T>%
    ggplot(aes(x = cyl, y = mpg)) 
    geom_line() %>%
    group_by(cyl) %>% 
    summarise(mpg = mean(mpg))

It gives the following error:

Error in UseMethod("group_by") : 
  no applicable method for 'group_by' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"

Why doesn't it work? From the %T>% documentation, I would expect that the left-hand side object, in this case, mtcars, would be returned after ggplot. Unfortunately that doesn't seem to work. Did I misunderstand the %T>% pipe? How is the code supposed to look like to make this work?

CodePudding user response:

You need to wrap the ggplot call in a print so you get both calls. You can use the following code:

library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.1.2
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'tidyr' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
#> Warning: package 'dplyr' was built under R version 4.1.2
library(magrittr)
#> Warning: package 'magrittr' was built under R version 4.1.2
#> 
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract
mtcars %T>%
  {print(ggplot(., aes(x = cyl, y = mpg)) 
  geom_line())} %>%
  group_by(cyl) %>% 
  summarise(mpg = mean(mpg))

#> # A tibble: 3 × 2
#>     cyl   mpg
#>   <dbl> <dbl>
#> 1     4  26.7
#> 2     6  19.7
#> 3     8  15.1

Created on 2022-06-30 by the reprex package (v2.0.1)

  • Related