带有dplyr的功能图 [英] Function graph with dplyr

查看:49
本文介绍了带有dplyr的功能图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个带有图的函数

I would to create a function with a graph

我的数据集如下:

Age   NAP
17    0,282
18    0,8282
19    0,223

age是函数中的变量Var

age is the variable Var in function

plot_stats_freq_continu <- function(df,  Var , y = NAP)
{

  df$sinistres <- rep(1,nrow(df))
  data_graph <- df %>% 
    group_by(!! Var)%>%
    summarise(Annee_police = sum(NAP), Nb_sinistres= sum(sinistres)) %>%  
    mutate(Fréquence = mean((Nb_sinistres/Annee_police)))     

  ndata_graph <-  as.data.frame(data_graph)
  p <- ggplot(data=data_graph, aes(x=Var)) +geom_density() +geom_point(data=data_graph, aes(x=Var, y= Fréquence))
  plot(p)
}

这是我的功能,当我尝试不带功能的代码时就走了,但是对功能来说却不行,

This is my function, it's walk when I try my code without function but it's not ok with function,

我遇到以下错误:


错误:美学的长度必须为1或与数据
(23)相同:x

Error: Aesthetics must be either length 1 or the same as the data (23): x


推荐答案

您可以尝试

plot_stats_freq_continu <- function(df,  Var){
  Var <- enquo(Var)
   df %>% 
    mutate(sinistres = 1) %>% 
    group_by(!!Var) %>%
    summarise(Annee_police = sum(NAP), Nb_sinistres= sum(sinistres)) %>%  
    mutate(Fréquence = mean((Nb_sinistres/Annee_police))) %>% 
  ggplot(aes_q(Var)) + 
    geom_density()+
    geom_point(aes_q(Var, quote(Fréquence)))
}

plot_stats_freq_continu(d, Age)

问题是ggplot无法识别 Var 。使用替代解决了此问题。

The problem was that the Var was not recognized by ggplot. Using substitute solves this issue.

这篇关于带有dplyr的功能图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆