0

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

xhr489
  • 1,957
  • 13
  • 39
  • 2
    You have passed a constant string (a name) as `y` aesthetic. Instead do `aes(y = !!sym(name))` or `aes(y = .data[[name]])` – Lionel Henry May 08 '19 at 12:05

1 Answers1

1

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

xhr489
  • 1,957
  • 13
  • 39