rplotconfidence-interval

Add confidence intervals to a plot


I've coded a martingale function, like this:

martingala <- function(bolsa, apuesta, limite, prob) {
  dinero <- bolsa
  betsize <- apuesta
  while(dinero >= betsize & betsize <= limite) {
    roll <- rbinom(1, 1, prob)
    if(roll == 1) {
      dinero <- dinero + betsize
      betsize <- betsize
    } else {
      dinero <- dinero - betsize
      betsize <- betsize * 2
    }
  }
  return(dinero)
}

Then I've coded a plot for the average results for different values of probability, from 0.2 to 0.6 in 0.01 steps, running the function 1000x:

x<- seq(.2, .6, .01)
m <- c()
n <- 1000
for (i in x){
  a <- c(replicate(n, martingala(100, 10, 500, i)))
    m <- c(m, mean(a))
    Up <- mean(a)+1.95*sd(a)/sqrt(n)
    Lo <- mean(a)+1.95-sd(a)/sqrt(n)
    }
plot(m, main = "Martingala probabilidad variable", xlab = "Probabilidad", ylab = "Ganancia media")

Any ideas about how I could add the Confidence Intervals (Up & Lo, respectively) to the plot? Thanks in advance.


Solution

  • There may be something wrong with your math here, but to address the specific coding problem of plotting the CIs - you are not creating a vector for Up and Lo, so they are being overwritten each iteration in the loop and only represent the last value of i (0.6).

    In your current code, you can correct that by creating a vector (albeit, growing vectors inside a loop is discouraged) then use lines to plot the CIs:

    x <- seq(.2, .6, .01)
    m <- c()
    n <- 1000
    Up <- c() # added
    Lo <- c() # added
    
    for (i in x){
      a <- replicate(n, martingala(100, 10, 500, i))
      m <- c(m, mean(a))
      Up <- c(Up, mean(a) + 1.95 * sd(a) / sqrt(n))  # added c()
      Lo <- c(Lo, mean(a) + 1.95 - sd(a) / sqrt(n)) # added c()
    }
    
    plot(m, main = "Martingala probabilidad variable", xlab = "Probabilidad", ylab = "Ganancia media")
    lines(Up)
    lines(Lo)
    

    enter image description here