0

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

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

Community
  • 1
  • 1
davidhen
  • 579
  • 6
  • 10
  • 1
    AgeGrp is being evaluated before you pass it to `basic_plot`. 1) change the line from `ggplot(df, aes(x = x))` to `ggplot(df, aes_(x = x))` and call the function as: `basic_plot(data, quote(AgeGrp))`. It should also be noted that this is entirely accomplishable without standard evaluation, but this could be a good learning example. – Chrisss Feb 17 '17 at 20:09
  • That's great - thanks. It totally works now. I'd be interested how to do this with NSE. The only reason I ended up looking at SE was because I couldn't get the function to work when I first wrote it with normal dplyr NSE code. – davidhen Feb 17 '17 at 22:01

0 Answers0