Skip to content

Instantly share code, notes, and snippets.

@expersso
Last active October 4, 2017 09:46
Show Gist options
  • Select an option

  • Save expersso/1ebbf437ec9e050b2c831299d9432c6c to your computer and use it in GitHub Desktop.

Select an option

Save expersso/1ebbf437ec9e050b2c831299d9432c6c to your computer and use it in GitHub Desktop.
Accumulate function that accepts a predicate for when to stop
# inspiration: https://twitter.com/MilesMcBain/status/915448555027828737
accumulate_until <- function(.x, .f, .p, ..., .init = NULL) {
n <- length(.x)
m <- mode(.x)
out <- vector(m, n)
if(!is.null(.init)) {
.x <- c(.init, .x)
}
out[1] <- .x[1]
for(i in seq(2, n)) {
y <- .f(out[i - 1], .x[i], ...)
if(.p(y)) return(out[seq_len(i - 1)])
out[i] <- y
}
out
}
accumulate_until(1:10, `+`, function(x) x > 10)
# [1] 1 3 6 10
transition_mc <- function(steps, start, mat, .p) {
i <- seq_len(nrow(mat))
transition <- function(x, y) sample(i, 1, prob = (i == x) %*% mat)
accumulate_until(seq_len(steps), transition, .p, .init = start)
}
transition_matrix <- rbind(c(.1, .9, 0), c(.45, .45, .1), c(0, 0, 1))
transition_mc(30, 2, transition_matrix, .p = function(x) x == 3)
# e.g. [1] 2 2 2 2 2 2 1 2 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment