0

I make this function in R to make a bar graph but it gives me an error every time I try it on a dataset, saying that columname is not found. Can you help me find where the bug is please.

Thanks in advance for your help on how to fix this.

Here is the code:

plot_dist <-
  function(data, column_name, title = "Please provide a title") {
    ## This function computes a barplot of a given column_name for a given dataset with the title
    data %>%
      group_by(column_name) %>%
      summarise(Nombre = n()) %>%
      ggplot(aes(column_name, Nombre)) +
      geom_bar(stat = "identity", fill = 'steelblue') +
      geom_text(
        aes(label = Nombre),
        vjust = -0.5,
        color = 'steelblue',
        size = 3.5
      ) +
      theme_minimal() +
      ggtitle(title) +
      theme(plot.title = element_text(hjust = 0.5))
}

For example running:

plot_dist(pps, gender, "Distribution de genre") 

returns

Error: Column column_name is unknown

neilfws
  • 32,751
  • 5
  • 50
  • 63
Theodule
  • 1
  • 1

1 Answers1

0

I think the simplest way to make this work with tidyeval is:

...
group_by({{ column_name}} ) %>%
      summarise(Nombre = n()) %>%
      ggplot(aes({{ column_name }}, Nombre)) +
...

plot_dist(mtcars, cyl, "Distribution de cilindros")

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53