Created
October 30, 2015 10:22
-
-
Save carlislerainey/f8cb897382bdc345178f to your computer and use it in GitHub Desktop.
Code to simulate and calculate the number of switches and streaks in a series of coin tosses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| calc_switches <- function(x) { | |
| n <- length(x) | |
| x0 <- x[1:(n - 1)] | |
| x1 <- x[2:n] | |
| switches <- sum(x0 != x1) | |
| return(switches) | |
| } | |
| calc_streak <- function(x) { | |
| longest_streak <- 0 | |
| current_streak <- 1 | |
| n <- length(x) | |
| for (i in 2:n) { | |
| current_streak <- ifelse(x[i] == x[i - 1], current_streak + 1, 1) | |
| longest_streak <- ifelse(current_streak > longest_streak, current_streak, longest_streak) | |
| } | |
| return(longest_streak) | |
| } | |
| x <- rbinom(50, 1, .5) | |
| calc_streak(x) | |
| n_sims <- 1000 | |
| switches <- longest_streak <- rep(NA, n_sims) | |
| for (i in 1:n_sims) { | |
| x <- rbinom(200, 1, .5) | |
| switches[i] <- calc_switches(x) | |
| longest_streak[i] <- calc_streak(x) | |
| } | |
| df <- data.frame(switches, longest_streak) | |
| library(ggplot2) | |
| ggplot(df, aes(x = switches, y = longest_streak)) + | |
| geom_point(position = "jitter") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment