Functional programming with dplyr

后端 未结 2 1276
臣服心动
臣服心动 2021-01-02 14:42

Looking for a more efficient / elegant way to pass multiple arguments to a group-by using non-standard evaluation in a function using dplyr. I don\'t want to use the ... ope

相关标签:
2条回答
  • 2021-01-02 15:02

    You could just do a straight eval.parent(substitute(...)) like this. Being base R it works consistently across R and is simple to do. One can even use an ordinary aes.

    plot_lines <- function(df, x, y, group) eval.parent(substitute(
       df %>%
          group_by(x, group) %>%
          my_smry %>%
          ggplot + geom_line(aes(x = x, y = y, group = group, color = group))
    ))
    plot_lines(my_df, month, conversion_rate, category)
    
    0 讨论(0)
  • 2021-01-02 15:21

    The problem is that ggplot hasn't been updated to handle quosures yet, so you've got to pass it expressions, which you can create from quosures with rlang::quo_expr:

    library(tidyverse)
    set.seed(47)
    
    my_df <- data_frame(month = sample(1:12, 1000, replace = TRUE),
                        category = sample(head(letters, 3), 1000, replace = TRUE),
                        approved = as.numeric(runif(1000) < 0.5),
                        converted = approved * as.numeric(runif(1000) < 0.5))
    
    plot_lines <- function(df, x, y, group) {
        x <- enquo(x)
        y <- enquo(y)
        group <- enquo(group)
    
        df %>%
            group_by(!! x, !! group) %>%
            summarise(conversion_rate = sum(converted) / sum(approved)) %>%
            ggplot(aes_(x = rlang::quo_expr(x), 
                        y = rlang::quo_expr(y), 
                        color = rlang::quo_expr(group))) + 
            geom_line()
    }
    
    my_df %>% plot_lines(month, conversion_rate, category)
    

    However, keep in mind that ggplot will almost inevitably be updated from lazyeval to rlang, so while this interface will probably keep working, a simpler, more consistent one will probably be possible shortly.

    0 讨论(0)
提交回复
热议问题