## Code

```
# Load the required packages
library(ggplot2)
library(scales) #use the percent scale later
# Create a function for running of the bets.
<- function(p, n, t, start=100, gain, loss, ergodic=FALSE, absorbing=FALSE){
bet
#p is probability of a gain
#n is how many people in the simulation
#t is the number of coin flips simulated for each person
#start is the number of dollars each person starts with
#if ergodic=FALSE, gain and loss are the multipliers
#if ergodic=TRUE, gain and loss are the dollar amounts
#if absorbing=TRUE, zero wealth ends the series of flips for that person
<- as.data.frame(c(p, n, t, start, gain, loss, ergodic, absorbing))
params rownames(params) <- c("p", "n", "t", "start", "gain", "loss", "ergodic", "absorbing")
colnames(params) <- "value"
<- matrix(data = NA, nrow = t, ncol = n)
sim
if(ergodic==FALSE){
for (j in 1:n) {
<- start
x for (i in 1:t) {
<- rbinom(n=1, size=1, prob=p)
outcome ifelse(outcome==0, x <- x*loss, x <- x*gain)
<- x
sim[i,j]
}
}
}
if(ergodic==TRUE){
for (j in 1:n) {
<- start
x for (i in 1:t) {
<- rbinom(n=1, size=1, prob=p)
outcome ifelse(outcome==0, x <- x-loss, x <- x+gain)
<- x
sim[i,j] if(absorbing==TRUE){
if(x<0){
:t,j] <- 0
sim[ibreak
}
}
}
}
}
<- rbind(rep(start,n), sim) #placing the starting sum in the first row
sim <- cbind(seq(0,t), sim) #number each period
sim <- data.frame(sim)
sim colnames(sim) <- c("period", paste0("p", 1:n))
<- list(params=params, sim=sim)
sim
sim
}
# Simulate 10,000 people who accept a series of 1000 50:50 bets to win \$50 or lose \$40 from a starting wealth of \$100.
set.seed(20200203)
<- bet(p=0.5, n=10000, t=1000, gain=50, loss=40, ergodic=TRUE, absorbing=FALSE)
ergodic
# Create a function for plotting the path of individuals in the population over a set number of flips.
<- function(sim, t, people){
individualPlot
<- ggplot(sim$sim[c(1:(t+1)),], aes(x=period)) +
basePlot labs(y = "Wealth ($)")
for (i in 1:people) {
<- basePlot +
basePlot geom_line(aes(y = !!sim$sim[c(1:(t+1)),(i+1)]), color = 2)
}
basePlot
}
# Plot both the average outcome and first twenty people on the same plot.
<- function(sim, t, subset) {
jointPlot individualPlot(sim, t, subset) +
geom_line(aes(y = rowMeans(sim$sim[c(1:(t+1)),2:(sim$params[2,]+1)])), color = 1, linewidth=1)
}
<- jointPlot(sim=ergodic, t=100, subset=20)
ergodicPlot ergodicPlot
```