Skip to content

Instantly share code, notes, and snippets.

@glamp
Created March 31, 2014 16:32
Show Gist options
  • Save glamp/9896325 to your computer and use it in GitHub Desktop.
Save glamp/9896325 to your computer and use it in GitHub Desktop.
# http://cran.r-project.org/web/packages/markovchain/vignettes/an_introduction_to_markovchain_package.pdf
library(markovchain)
initialState <- c(0,1,0)
weatherStates <- c("sunny", "cloudy", "rain")
byRow <- TRUE
trans.probs <- matrix(data=c(0.7, 0.2, 0.1,
0.3, 0.4, 0.3,
0.2, 0.45, 0.35), byrow=TRUE, nrow=3,
dimnames = list(weatherStates, weatherStates))
mcWeather <- new("markovchain", states=weatherStates, transitionMatrix=trans.probs, name="Weather")
transitionProbability(mcWeather, "cloudy", "sunny")
transitionProbability(mcWeather, "cloudy", "cloudy")
transitionProbability(mcWeather, "cloudy", "rain")
initialState <- c(0,1,0)
# after 3 days
initialState * (mcWeather * mcWeather * mcWeather)
# after 7 days
initialState * (mcWeather^7)
print(mcWeather)
show(mcWeather)
mcWeather.df <- as(mcWeather, "data.frame")
mcIgraph <- as(mcWeather, "igraph")
show(mcIgraph)
# simulating your markov chain; t0 is initial state
weathersOfDays <- rmarkovchain(n = 365, object = mcWeather, t0 = "cloudy")
weathersOfDays[1:10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment