Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

r - Function graph with dplyr

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...