Monte Carlo Simulations

Monte Carlo simulation demonstration

library(dplyr)

## create function for hasek
hasek <- function(number_of_games, verbose = TRUE) {
  tally <- c()
  for (i in 1:number_of_games) {
    x <- runif(31)
    y <- x > 0.924

    z <- runif(26)
    w <- z > 0.90

    if (sum(w) > sum(y)) {
      result <- 2
    } else if (sum(w) < sum(y)){
      result <- 1
    } else {
      result <- 0
    }
    tally <- rbind(tally, result)
  }

  wins <- sum(tally == 2)
  losses <- sum(tally == 1)
  ties <- sum(tally == 0)

  df <- data.frame(wins = wins,
                   losses = losses,
                   ties = ties,
                   per = wins/(wins + losses))

  if (verbose == TRUE) {
    cat("Sabres have ", wins, " wins and ", losses, "losses and ", ties, " ties")
  } else {
    return(df)
  }
}

hasek(82)
hasek(82)
hasek(82)

## create function for average goalie
avg_goalie <- function(number_of_games, verbose = TRUE) {
  tally <- c()
  for (i in 1:number_of_games) {
    x <- runif(31)
    y <- x > 0.90

    z <- runif(26)
    w <- z > 0.90

    if (sum(w) > sum(y)) {
      result <- 2
    } else if (sum(w) < sum(y)){
      result <- 1
    } else {
      result <- 0
    }
    tally <- rbind(tally, result)
  }

  wins <- sum(tally == 2)
  losses <- sum(tally == 1)
  ties <- sum(tally == 0)

  df <- data.frame(wins = wins,
                   losses = losses,
                   ties = ties,
                   per = wins/(wins + losses))

  if (verbose == TRUE) {
    cat("Sabres have ", wins, " wins and ", losses, "losses and ", ties, " ties")
  } else {
    return(df)
  }
}

avg_goalie(82)
avg_goalie(82)
avg_goalie(82)

set.seed(111320)

## run hasek function 1000 times and doctor up result
winning_percentage_hasek <- lapply(rep(82, 1000), hasek, verbose = FALSE) %>%
  lapply(., `[[`, 4) %>%
  unlist

set.seed(111321)

## run avg function 1000 times and doctor up result
winning_percentage_avg <- lapply(rep(82, 1000), avg_goalie, verbose = FALSE) %>%
  lapply(., `[[`, 4) %>%
  unlist

## view results
summary(winning_percentage_hasek)
summary(winning_percentage_avg)

## how many wins is hasek worth?
summary(winning_percentage_hasek)[4] * 82 -
  summary(winning_percentage_avg)[4] * 82