-1

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

pogibas
  • 27,303
  • 19
  • 84
  • 117
Naï
  • 53
  • 6

2 Answers2

1

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.

Roman
  • 17,008
  • 3
  • 36
  • 49
  • @Naï Edited my answer to use piping until the end. If you`re happy with it, please consider to accept the answer. – Roman Apr 04 '18 at 09:22
-1

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.

Amar
  • 1,340
  • 1
  • 8
  • 20