Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I end a dplyr pipe with NULL? to allow easy comment/uncomment

Tags:

r

dplyr

ggplot2

library(tidyverse)
ggplot(mpg, aes(hwy)) + 
  geom_histogram() + 
  theme_classic() + 
  NULL

Do you remember the cool trick ending your ggplot commands with NULL to allow the easy commenting/uncommenting of lines within your code? Compare the chunk above to the chunk below. In this example I'll comment out theme_classic() + and my code still works fine, since NULL is at the end.

ggplot(mpg, aes(hwy)) + 
  geom_histogram() + 
  # theme_classic() + 
  NULL

OK. So how do I do the same thing with a dplyr pipe? I want to put the NULL at the end so I could comment/uncomment the count(cyl) at will. But it doesn't quite work. I get an Error in .() : could not find function ".".

mtcars %>% 
  as_tibble() %>% 
  count(cyl) %>% 
  NULL

mtcars %>% 
  as_tibble() %>% 
  # count(cyl) %>% 
  NULL
like image 497
stackinator Avatar asked Oct 01 '18 17:10

stackinator


1 Answers

I've seen I() ("asis") used for this (I think on twitter, but can't seem to re-find the conversation):

mtcars %>% 
     as_tibble() %>% 
     # count(cyl) %>% 
     I()

Note that using I() prepends the class "AsIs" on the object. There is a possibility that this could lead to unintended consequences if using the assigned object in some later step.

Other possibilities from comments that all appear to work without the I() side effect:
identity() or force()
print() or {.} or return()

like image 131
aosmith Avatar answered Oct 22 '22 03:10

aosmith