Skip to content

Instantly share code, notes, and snippets.

@thoolihan
Created June 30, 2017 17:42
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 thoolihan/fd426c226bfbd07ffbc52a151b856bc5 to your computer and use it in GitHub Desktop.
Save thoolihan/fd426c226bfbd07ffbc52a151b856bc5 to your computer and use it in GitHub Desktop.
Simulate 2 state Markov Chain from Wikipedia
# simulating https://en.wikipedia.org/wiki/Markov_chain#/media/File:Markovkate_01.svg
library(ggplot2)
means = c()
ntimes <- 1000
for (t in 1:ntimes) {
n <- 1000
state <- c(1)
chaos <- runif(n)
for(i in 1:(length(chaos) - length(state))) {
current <- state[length(state)]
if (current == 1) {
if (chaos[i] <= .4) {
state <- c(state, 0)
} else {
state <- c(state, 1)
}
} else {
if (chaos[i] <= .7) {
state <- c(state, 1)
} else {
state <- c(state, 0)
}
}
}
state <- factor(state, labels = c('e', 'a'))
means <- c(means, mean(state == 'e'))
}
qplot(means, geom="histogram", binwidth = .005) +
geom_vline(xintercept = mean(means), color = 'blue')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment