xhr489
xhr489

Reputation: 2339

Tidyeval in a function with dplyr and ggplot2

So I create the name with :=, but I want to use it in ggplot2 as y which does not seem to work.

library(tidyverse)
date_group_plot_line <- function(df, group_col, summarise_col) {
  group_col  <-enquo(group_col)
  summarise_col <- enquo(summarise_col)

  name <- paste0(rlang::quo_name(summarise_col), "_", "mean")

  df %>%
    dplyr::group_by(!!group_col) %>%
    dplyr::summarise( !!name := mean(!!summarise_col)) %>%
    dplyr::filter(!is.na(!!group_col)) %>%
    ggplot2::ggplot(ggplot2::aes(x=!!group_col, y= !!name )) +
    ggplot2::geom_point()
}

date_group_plot_line(diamonds, cut, price)
#> Warning: package 'bindrcpp' was built under R version 3.4.4

Created on 2019-05-08 by the reprex package (v0.2.0).

Upvotes: 0

Views: 51

Answers (1)

xhr489
xhr489

Reputation: 2339

With the help of @LionelHenry in the comment section of the question here is my own answer:

library(tidyverse)

date_group_plot_line <- function(df, group_col, summarise_col) {
  group_col  <-enquo(group_col)
  summarise_col <- enquo(summarise_col)

  name <- paste0(rlang::quo_name(summarise_col), "_", "mean")

  df %>%
    dplyr::group_by(!!group_col) %>%
    dplyr::summarise( !!name := mean(!!summarise_col)) %>%
    dplyr::filter(!is.na(!!group_col)) %>%
    ggplot2::ggplot(ggplot2::aes(x=!!group_col, y= !!rlang::sym(name) )) +
    ggplot2::geom_point()
}

date_group_plot_line(diamonds, cut, price)
#> Warning: package 'bindrcpp' was built under R version 3.4.4

Created on 2019-05-08 by the reprex package (v0.2.0).

Upvotes: 1

Related Questions