Programming with ggplot2 and dplyr

后端 未结 2 1119
-上瘾入骨i
-上瘾入骨i 2021-01-01 06:32

I want to combine dplyr and ggplot within one function using piping and struggling with some issues now.

Here is the first easy one which

相关标签:
2条回答
  • 2021-01-01 07:11

    ggplot2 v3.0.0 released in July 2018 supports !! (bang bang), !!!, and :=.

    facet_wrap() and facet_grid() support vars() inputs. The first two arguments of facet_grid() become rows and cols. facet_grid(vars(cyl), vars(am, vs)) is equivalent to facet_grid(cyl ~ am + vs) and facet_grid(cols = vars(am, vs)) is equivalent to facet_grid(. ~ am + vs).

    So your example can be modified as follow:

    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`.
    

    Created on 2018-04-04 by the reprex package (v0.2.0).

    0 讨论(0)
  • 2021-01-01 07:25

    @Tung's answer can be simplified using {{ syntax. https://rlang.r-lib.org/reference/quasiquotation.html

    library(rlang)
    library(dplyr)
    library(ggplot2)
    
    foo <- function(df, y, gr, t = 4) {
      df %>% 
        filter({{ y }}> t) %>% 
        ggplot(aes({{ y }})) + 
        geom_histogram() +  
        facet_grid(cols = vars({{ gr }}))
    }
    
    foo(mtcars, y = cyl, gr = vs)
    
    0 讨论(0)
提交回复
热议问题