如何以NULL结束dplyr管道?允许轻松评论/取消评论

sta*_*tor 8 r ggplot2 dplyr

library(tidyverse)
ggplot(mpg, aes(hwy)) + 
  geom_histogram() + 
  theme_classic() + 
  NULL
Run Code Online (Sandbox Code Playgroud)

你还记得结束你的ggplot命令的酷炫技巧NULL,以便在代码中轻松注释/取消注释行吗?将上面的块与下面的块进行比较.在这个例子中,我将注释掉theme_classic() +,我的代码仍然正常,因为NULL最后.

ggplot(mpg, aes(hwy)) + 
  geom_histogram() + 
  # theme_classic() + 
  NULL
Run Code Online (Sandbox Code Playgroud)

好.那么如何使用dplyr管道做同样的事情呢?我想把它放在NULL最后,这样我就可以随意评论/取消注释count(cyl).但它不太有效.我得到了Error in .() : could not find function ".".

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

mtcars %>% 
  as_tibble() %>% 
  # count(cyl) %>% 
  NULL
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 8

我见过I()("asis")用于此(我想在推特上,但似乎无法重新找到对话):

mtcars %>% 
     as_tibble() %>% 
     # count(cyl) %>% 
     I()
Run Code Online (Sandbox Code Playgroud)

请注意,使用I()prepends "AsIs"对象的类.如果在稍后的步骤中使用指定的对象,则可能会导致意外后果.

评论的其他可能性似乎都没有I()副作用:
identity()or force()
print(){.}orreturn()

  • 或者`force`或`identity`作为他们的代码真的是`function(x)x` (3认同)
  • 也可以使用`{.}`.`I`更改了对象的类,如果分配了输出,可能会产生意想不到的后果 (2认同)