I have data with lots of factor variables that I am visualising to get a feel for each of the variables. I am reproducing a lot of the code with minor tweaks for variable names etc. so decided to write a function to simply things. I just can't get it to work...
Dummy Data
ID <- sample(1:32, 128, replace = TRUE)
AgeGrp <- sample(c("18-65", "65-75", "75-85", "85+"), 128, replace = TRUE)
ID <- factor(ID)
AgeGrp <- factor(AgeGrp)
data <- data_frame(ID, AgeGrp)
data
Basically what I am trying to do with each factor variable is produce a bar chart with labels of percentages inside the bars. For example with the dummy data.
plotstats <-   #Create a table with pre-summarised percentages                    
  data %>%                    
  group_by(AgeGrp) %>%                
  summarise(count = n()) %>% 
  mutate(pct = count/sum(count)*100)  
age_plot <-     #Plot the data            
    ggplot(data,aes(x = AgeGrp)) +
    geom_bar() +                    #Add the percentage labels using pre-summarised table
    geom_text(data = plotstats, aes(label=paste0(round(pct,1),"%"),y=pct),
                                    size=3.5, vjust = -1, colour = "sky blue") +
    ggtitle("Count of Age Group")
age_plot

This works fine with the dummy data - but when I try to create a function...
 basic_plot <- 
        function(df, x){
        plotstats <-
        df %>%
        group_by_(x) %>%               
        summarise_(
                   count = ~n(),
                   pct = ~count/sum(count)*100)
       plot <-                   
         ggplot(df,aes(x = x)) +
         geom_bar() + 
         geom_text(data = plotstats, aes(label=paste0(round(pct,1),"%"),
                                    y=pct), size=3.5, vjust = -1, colour = "sky blue")
    plot
  }
basic_plot(data, AgeGrp)
I get the error code :
Error in UseMethod("as.lazy") : no applicable method for 'as.lazy' applied to an object of class "factor"
I have looked at questions here, here, and here and also looked at the NSE Vignette but can't find my fault.