dplyr and ggplot piping is not working as expected

Viewed 1225

I find no solution for these two following issues:

First I try this:

library(tidyverse)
gg <- mtcars %>% 
      mutate(group=ifelse(gear==3,1,2)) %>%      
      ggplot(aes(x=carb, y=drat)) + geom_point(shape=group)

Error in layer(data = data, mapping = mapping, stat = stat, geom = 
GeomPoint,:object 'group' not found

which is obviously not working. But using something like this .$group is also not successfull. Of note, I have to specifiy the shape outside from aes()

The second problem is this. I'm not able to call a saved ggplot (gg) within a pipe.

gg <- mtcars %>% 
      mutate(group=ifelse(gear==3,1,2)) %>%      
      ggplot(aes(x=carb, y=drat)) + geom_point()


    mtcars %>% 
        filter(vs == 0) %>% 
        gg + geom_point(aes(x=carb, y=drat), size = 4)  

Error in gg(.) : could not find function "gg"

Thanks for your help!

Edit

After a long time I found a solution here. One has to set the complete ggplot term in {}.

mtcars %>% 
   mutate(group=ifelse(gear==3,1,2)) %>% {     
   ggplot(.,aes(carb,drat)) +
       geom_point(shape=.$group)}
1 Answers
Related