Skip to content

Instantly share code, notes, and snippets.

@zkamvar
Created October 4, 2017 15:22
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 zkamvar/e1698289064d3445255236c50e7c71a0 to your computer and use it in GitHub Desktop.
Save zkamvar/e1698289064d3445255236c50e7c71a0 to your computer and use it in GitHub Desktop.
@drob's purrr MC
# This is from @drob on twitter:
#
# https://twitter.com/drob/status/915378838078722048
#
library("purrr")
transition_mc <- function(steps, start, mat){
i <- seq_len(nrow(mat))
transition <- ~ sample(i, prob = (i == .) %*% mat)
accumulate(seq_len(steps), transition, .init = start)
}
# Example: 1 wants to go to 2, 2 could go back to 1, 3 is absorbing
transition_matrix <- rbind(
c(0.10, 0.90, 0.00),
c(0.45, 0.45, 0.10),
c(0.00, 0.00, 1.00)
)
# 30 steps starting in state 2
transition_mc(30, 2, transition_matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment