I am not immediately aware of a "built-in" function (e.g., in
base or similar), but we can do this very easily and efficiently in a couple of lines of code.
Here is a function that takes a matrix (not a data frame) as an input and produces either the transition counts (
prob=FALSE) or, by default (
prob=TRUE), the estimated transition probabilities.
# Function to calculate first-order Markov transition matrix.
# Each *row* corresponds to a single run of the Markov chain
trans.matrix <- function(X, prob=T)
tt <- table( c(X[,-ncol(X)]), c(X[,-1]) )
if(prob) tt <- tt / rowSums(tt)
If you need to call it on a data frame you can always do
If you're looking for some third-party package, then Rseek or the R search site may provide additional resources.