Skip to content

Instantly share code, notes, and snippets.

@AndreaCirilloAC
Last active August 10, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCirilloAC/9224516abe532f4373669571f887eeb7 to your computer and use it in GitHub Desktop.
Save AndreaCirilloAC/9224516abe532f4373669571f887eeb7 to your computer and use it in GitHub Desktop.
a simple function to simulate geometric distribution for a given p of success and number of trials, producing a ggplot bar plot of the distribution
require(ggplot2)
#bernoulli
bernoulli_trial <- function(p_succ,n_trials){ # probability of success (1) and number of trials
p_insucc <- 1-p_succ # rpobability of failure
trials <<- c()
p_cumulative <<- c()
for(i in 1:n_trials){
trials <<- rbind(trials,i)
p_cumulative <<- rbind(p_cumulative,(((p_insucc)^(i -1))*p_succ)) # (p of success within n trials) = ((1-p)^n-1)*(p)
}
results <<- data.frame(trials,p_cumulative)
g <<- ggplot(results,aes(x=trials,y=p_cumulative))+
geom_bar(stat ='identity')
g
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment