与dplyr,tidyr和ggplot一起使用

时间:2017-07-05 14:39:20

标签: r ggplot2 dplyr tidyr tidyeval

如何创建一个带有列的函数并在dplyr,tidyr和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))

如何编写函数需要参数param_col而不是硬编码的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() 

dplyr和ggplot调用在下面列出的代码中工作。但是如何编写complete调用?或者应该使用complete_

是否有更规范的方式来做到这一点?

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()
}

1 个答案:

答案 0 :(得分:1)

tidyr 的开发版本,tidyr_0.6.3.9000,现在使用tidyeval,因此如果您想要更新,那么您可以使用!! 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()
}

使用当前版本,您可以将complete_变量用作字符串。

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()
}