使用dplyr在函数内部进行标准评估

时间:2017-02-17 19:53:04

标签: r dplyr nse

我有大量因子变量的数据,我可以通过这些变量来了解每个变量。我正在复制很多代码,对变量名等进行微调。因此决定编写一个简单的函数。我只是无法让它工作......

虚拟数据

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

基本上我要对每个因子变量做的是产生一个条形图,条形图中有百分比标签。例如,使用虚拟数据。

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

这适用于虚拟数据 - 但是当我尝试创建函数时......

 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)

我收到错误代码:

  

UseMethod(“as.lazy”)中的错误:没有适用于“as.lazy”的方法应用于类“factor”的对象

我查看了问题hereherehere,并查看了NSE Vignette,但找不到我的错。

0 个答案:

没有答案
相关问题