使用ggplot2和dplyr进行编程

3

我希望通过使用流水线结合 dplyrggplot 来创建一个函数,并且目前正在解决一些问题。

下面是第一个简单的成功实现的功能。这个函数接受一个数据框并按指定列和值进行筛选。

foo <- function(df, y, t = 4){
  tmp <- df %>% 
          filter(!!enquo(y) > t)
  ggplot(tmp, aes_(substitute(y))) + 
      geom_histogram()  
}
foo(mtcars, cyl)

现在我试图直接将内容导入到ggplot函数中,却报错了。

foo <- function(df, y, t=4){
  df %>% 
     filter(!!enquo(y) > t) %>% 
        ggplot(aes_(substitute(y))) + 
            geom_histogram()  
}
foo(mtcars, cyl)

在 FUN(X[[i]], ...) 中出现错误:未找到对象 'cyl' 此外:警告信息: 在 FUN(X[[i]], ...) 中:重新启动被中断的 promise 评估

最后一个问题。如何添加 facet?

foo <- function(df, y, gr, t=4){
  df %>% 
       filter(!!enquo(y) > t) %>% 
  ggplot(aes_(substitute(y))) + 
      geom_histogram() +  
      facet_grid(~gr)
}
foo(mtcars, y= cyl, gr= vs)

编辑

使用aes_q代替aes_substitute可以解决第二个问题。 来源

foo <- function(df, y, gr, t=4){
  y <- enquo(y)
  df %>% 
    filter(!!y > t) %>% 
       ggplot(aes_q(y)) + 
           geom_histogram()
}
foo(mtcars, cyl)

使用ggplot2_2.2.1

2个回答

4
ggplot2 v3.0.0于2018年7月发布,支持!!(叹号叹号)、!!!:=facet_wrap()facet_grid()支持vars()输入。 facet_grid()的前两个参数成为rowscolsfacet_grid(vars(cyl), vars(am, vs))等效于facet_grid(cyl ~ am + vs)facet_grid(cols = vars(am, vs))等效于facet_grid(. ~ am + vs)。 因此,您的示例可以修改如下:
library(rlang)
library(tidyverse)

foo <- function(df, y, gr, t=4) {
  y <- enquo(y)
  gr <- enquo(gr)

  df %>% 
    filter(!!y > t) %>% 
    ggplot(aes(!!y)) + 
    geom_histogram() +  
    facet_grid(cols = vars(!!gr))
}

foo(mtcars, y= cyl, gr= vs)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

此内容于2018-04-04通过reprex软件包 (v0.2.0)创建。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接