Function graph with dplyr

2019-09-20 13:21发布

I would to create a function with a graph

My dataset is like that :

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

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,

I have the following error :

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

2条回答
狗以群分
2楼-- · 2019-09-20 14:04

You can try

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)

enter image description here

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

查看更多
forever°为你锁心
3楼-- · 2019-09-20 14:11

This is an issue with your data. I ran your code on the data you have provided (but i removed the , from the numbers) and your code worked fine. Unless you provide example data and a reproducible example we can not help you.

I am going to guess it has something to do with this chunk:

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

The computation in the above code is probably producing Fréquence that is shorter than your data (which the error states is 23). I'm going to guess this code is silently erroring out and producing an empty data.frame. Also this line:

ndata_graph <- as.data.frame(data_graph)

is either redundant/unused.

查看更多
登录 后发表回答