Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...