Last active
August 29, 2015 14:26
-
-
Save nelsonauner/2b90e35b4fa4974bf709 to your computer and use it in GitHub Desktop.
Transition probabilies: generating and displaying
This file contains 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
############################################# | |
# Simulation ################## | |
############################################# | |
set.seed(225+1600) | |
num_users <- 1000 | |
#define transition probabilities between states | |
start_probs <- c("check" = .7, "save" = .2, "both" = .1) | |
check <- c("check" = .6, "save" = .05, "both" = .3, "none" = .05) | |
save <- c("check" = .1, "save" = .8, "both" = .05, "none" = .05) | |
both <- c("check" = .2, "save" = .2, "both" = .6, "none" = 0) | |
transition_matrix <- rbind( | |
check, | |
save, | |
both | |
) | |
cumulative_transition_matrix <- t(apply(transition_matrix,1,cumsum)) | |
## create data ### | |
users <- data.frame( | |
date = 1, | |
id = sample(num_users:(num_users*10),size=num_users,replace=FALSE), | |
finst = sample(names(start_probs),size=num_users,prob=start_probs,replace=TRUE), | |
stringsAsFactors = FALSE | |
) | |
## function to generate next day's state | |
markovTransition <- function(state_vector,trans_prob) { | |
# function to take a user and run transition probability | |
l = length(state_vector) | |
rands = runif(l) | |
result = rep(NA,l) | |
for (i in 1:l) { | |
(state <- state_vector[i]) | |
result[i] = names(trans_prob[state,])[(sum(trans_prob[state,] < rands[i])+1)] | |
} | |
return(result) | |
} | |
## let's generate for tomorrow ## | |
usersday2 <- data.frame( | |
date = 2, | |
id = users$id, | |
finst = markovTransition(users$finst,cumulative_transition_matrix), | |
stringsAsFactors = FALSE | |
) | |
This file contains 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
############################################# | |
# Actual solution ################## | |
############################################# | |
library(dplyr) | |
combined <- left_join(users,usersday2,by="id") | |
table(combined$finst.x,combined$finst.y)[c("check","save","both"),c("check","save","both", "none")] | |
# check save both none | |
# check 415 43 215 37 | |
# save 20 154 10 10 | |
# both 24 15 57 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment