Search code examples
rmarkov-chainsmarkov-models

Markov chain fit from many individual chains (in R)


Using the markovchain package, I'm working with a dataset comprised of six monthly observations for each of 23k individuals.

When I go to fit a DTMC using the markovchainFit function, the function appears to want to take in what would be just one of my 23k individuals. How can I fit a DTMC on the full population of 23k 6-period sequences?

(FYI - I'm able to calculate/plot/describe/etc. the MC just fine - I just want to be able to generate some clean predictions and take advantage of the rest of the package's functionality, and for that it seems I need a fitted MC object?)

So: how can I fit a MC object using markovchain or another package using a bunch of observations of the same 6-period sequence, and which will let me then generate some predictions for future steps?


Solution

  • The markovchainFit function can handle matrix, data.frame and list as input:

    library(markovchain)
    #getting from matrix / data.frame
    data(holson) #load a data.frame (also it works with matrices)
    head(holson) #load a matrix of pop * time observations
    singleMc<-markovchainFit(data=holson[,2:7],name="holson") #fit the MC
    
    #getting from list
    myList<-list()
    for (i in 1:100) {
      myList[[i]]<-sample(x = c("a","b"),size = 6,replace = TRUE,prob = c(0.5,0.5))
    }
    singleMcFromList<-markovchainFit(data=myList,name="holson") #fit the MC