简体   繁体   English

dplyr + magrittr + qplot =没有情节?

[英]dplyr + magrittr + qplot = no plot?

I want to use qplot (ggplot2) and then forward the data with magrittr : 我想用qplot (GGPLOT2),然后将数据转发与magrittr

This works: 这有效:

mtcars %>% qplot(mpg, cyl, data=.)

This produces an error: 这会产生错误:

mtcars %>% qplot(mpg, cyl, data=.) %>% summarise(mean(mpg))

And those produce only summary statistics: 这些只产生汇总统计:

mtcars %T>% qplot(mpg, cyl, data=.) %>% summarise(mean(mpg))
mtcars %>% {qplot(mpg, cyl, data=.); .} %>% summarise(mean(mpg))
mtcars %T>% {qplot(mpg, cyl, data=.)} %>% summarise(mean(mpg))

What is the problem? 问题是什么? I already found this solution, but it does not help, as you see from the code attached. 我已经找到了这个解决方案,但是从附带的代码中可以看出它没有帮助。

All ggplot2 functions return an object that represents a plot - to see it you need to print it. 所有ggplot2函数都返回一个表示绘图的对象 - 要查看它需要打印它。 That normally happens automatically when you're working in the console, but needs to explicit inside a function or a chain. 这通常在您在控制台中工作时自动发生,但需要在函数或链中明确显示。

The most elegant solution I could come up with is this: 我能想出的最优雅的解决方案是:

library("ggplot2")
library("magrittr")
library("dplyr")

echo <- function(x) {
  print(x)
  x
}
mtcars %>% 
  {echo(qplot(mpg, cyl, data = .))} %>% 
  summarise(mean(mpg))

It seems like there should be a better way. 似乎应该有更好的方法。

This seems more clean to me, because it does not require using %T>% (which IMHO makes a pipe harder to re-arrange and read) and no {} around the expression to avoid passing the object there. 这对我来说似乎更干净,因为它不需要使用%T>% (IMHO使管道更难以重新排列和读取)并且在表达式周围没有{}以避免将对象传递到那里。 I'm not sure how much harm there is in passing the object and ignoring it. 我不确定传递对象并忽略它有多大的伤害。

I've never had a use for the %T>% tee where I didn't also want to print or plot. 我从来没有使用%T>% tee,我不想打印或绘图。 And I never wanted to print/plot the object being piped itself (usually a big dataset). 而且我从来不想打印/绘制被自己管道的对象(通常是一个大数据集)。 So I never use %T>% . 所以我从不使用%T>%

library("ggplot2")
library("dplyr")


pap = function(pass, to_print = NULL, side_effect = NULL) {
  if( !is.null(to_print)) {
    if (is.function(to_print)) {
      print(to_print(pass))
    } else {
      print(to_print)
    }
  }
  side_effect
  invisible(pass)
}

mtcars  %>% 
   pap(summary) %>% 
   pap(side_effect = plot(.)) %>% 
   pap(qplot(mpg, cyl, data = .)) %>% 
   summarise(mean(mpg))

I usually don't use plotting as side-effect in my pipes, so the solution above works best for me (requires "extra typing" for side-effect plot). 我通常不会在我的管道中使用绘图作为副作用,所以上面的解决方案最适合我(对于副作用图需要“额外打字”)。 I'd like to be able to disambiguate between these intended scenarios (eg plot vs. qplot) automatically, but haven't found a reliable way. 我希望能够自动消除这些预期场景(例如情节与qplot)之间的歧义,但是没有找到可靠的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM