Creating function for generating graphs

Can someone help me with this. I'm analysing data and database includes more than 200 columns. As most of the data are really basic I want to create function that will enable me to generate graph by entering name of column. Columns are coded from 1 to 200 and they include letter C_ as prefix. When I create function it all works fine until I add code to group by name of column. Than I get the message column name unknown. I have tried everything that I'm aware of to avoid this issue but so far I haven't been very successful.

Code used is bellow and output that I get when I add group by is attached.With_group_by

Disclaimer: SS in the name of database stands for Satisfaction Survey:)

gen_graph <- function(x){
  
 data <- read_excel("SS_db.xlsx")
    
 test <-  data%>%
    #group_by(x) %>%
    mutate(n = 1) %>%
    drop_na(x) %>%
    dplyr::summarise(Total = sum(n)) %>%
    ggplot()+
    geom_col(aes(x, Total))+
    theme_classic()+
    scale_fill_viridis(discrete = T)+
    theme(
      legend.position = "none"
    )
  
  test
  
}

gen_graph("C_103")

Thx

I don't have access to your Excel file, so I've used mtcars for an example of how you can make it work:

library(tidyverse)


gen_graph <- function(x){
  x <- rlang::sym(x)
  
  test <-  mtcars %>%
    dplyr::group_by(!!x) %>%
    dplyr::mutate(n = 1) %>%
    tidyr::drop_na(!!x) %>%
    dplyr::summarise(Total = sum(n)) %>%
    ggplot() +
      geom_col(aes(!!x, Total)) +
      theme_classic() +
      theme(legend.position = "none")
    
  test
}

gen_graph("cyl")

gen_graph("gear")

Created on 2020-03-31 by the reprex package (v0.3.0)

2 Likes

Thank you very much. This was indeed solution to my problem. You saved my day. Thx

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.