Rickard
Rickard

Reputation: 3690

Function with dplyr, tidyr and ggplot

How can I make a function that takes a column and uses that in dplyr, tidyr and ggplot?

df <- data.frame(date_col = c(1,1,2,2,3,4,4,5,5), 
                 col_a = c('a','b','a','b','a','a','b','a','b'),
                 val_col = runif(9))

How do I write a function takes a parameter param_col instead of the hardcoded col_a

df %>% 
  group_by(date_col, col_a) %>% 
  summarise(val_col = sum(val_col)) %>% 
  complete(col_a, date_col) %>% 
  ggplot(aes(date_col, val_col, color = col_a)) + 
  geom_line() 

The dplyr and ggplot calls work in the code outlined below. But how should the complete call be written? Or should complete_ be used?

Is there a more canonical way of doing this?

plot_nice_chart <- function(df, param_col) {

  enq_param_col <- enquo(param_col)
  str_param_col <- deparse(substitute(param_col))


  # aggregate data based on group_by_col, 
  # explicitly fill in NA's for missing to avoid interpolation
  df %>% 
     group_by(!!enq_param_col, date_col) %>%
     summarise(val_col = sum(val_col)) %>%
     complete(<what-should-be-here?>, date_col) %>%
     ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
        geom_line()
}

Upvotes: 1

Views: 202

Answers (1)

aosmith
aosmith

Reputation: 36114

The development version of tidyr, tidyr_0.6.3.9000, now uses tidyeval, so if you want to update to that you could use !! as you did in group_by.

plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))
     str_param_col
     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete(!!enq_param_col, date_col) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}

Using the current version, you can use complete_ with variables as strings.

plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))

     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete_( c(str_param_col, "date_col") ) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}

Upvotes: 1

Related Questions