I'm attempting to generate a sample from an n-order transition matrix using Markov Chains in R. I've successfully constructed this n-order transition matrix using the following code:
set.seed(1)
dat <- sample(c("A", "B", "C"), size = 2000, replace = TRUE) # Data
n <- 2 # Order of the transition matrix
if (n > 1) {
from <- head(apply(embed(dat, n)[, n:1], 1, paste, collapse = ""), -1)
to <- dat[-1:-n]
} else {
from <- dat[-length(dat)]
to <- dat[-1]
}
fromTo <- data.frame(cbind(from, to))
TM <- table(fromTo)
TM <- TM / rowSums(TM) # Transition matrix
However, I'm facing difficulties in writing a code that generates a sample using the generated transition matrix which adapts to varying values of n. Is there a way to do it?
Ideally, I'd prefer a solution that doesn't involve the 'markovchain' package due to compatibility issues across different R versions.
Update
If you are just wondering how to generate a sample from the given transition matrix, you can try the code below for example (on top of the
MarkovChainfunction built in the previous answer)such that
Previous
I think you are after the transition matrix of Markov Chain of order
n. Below is one option where you might find some clues.You can use
embedlike belowand you will obtain