0

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

虚拟数据

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”的方法应用于“因子”类的对象

我在这里这里这里查看了问题,还查看了NSE Vignette,但找不到我的错。

4

0 回答 0