Jonathan Hilpert
Jonathan Hilpert

Reputation: 11

First Order Markov Transition Matrix for Person Period Data

Using time series data for a single person, I can calculate a first order probability transition matrix i.e.library(markovchain)and calculate its density i.e.library(statnet)

This code works:

ds = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8),ncol=3,byrow=TRUE) #create person period data for a single person
colnames(ds) = c("Id", "Time", "Evt")
ds = as.data.frame(ds)
mc = markovchainFit(ds$Evt, name = "mc")$estimate #calculate markovchain
am = mc@transitionMatrix #remove slot from S4 object
em = network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE) #make network object
gden(em)#calculate density of network, etc

But I am having trouble making it work for a data with multiple ID's using tapply. This code doesn't work after line 4, but it is how a solution looks in my head:

ds2 = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8,2,1,3,2,2,5,2,3,7,2,4,9),ncol=3,byrow=TRUE) #create person period data for two people
colnames(ds2) = c("Id", "Time", "Evt")
ds2 = as.data.frame(ds2)
mc2 = tapply(ds2$Evt, ds2$Id, markovchainFit) #it works to here and I am STUCK for days *see below
am2 = mc@transitionMatrix, #can't figure how to integrate these steps from above
em2 = network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE) 
gden(em2)

*For each person in the list I can't figure out:

  1. how to name the markov chain S4 object
  2. how to remove the transition matrix slot from the S4 object
  3. how to pass additional functions after markovchainFit

Does anybody have any suggestions about how to loop my analysis for a single person through an ID vector? It would be very much appreciated.

Upvotes: 1

Views: 161

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 22044

How about something like below. In the code below, I make a function that does all of the interim work and returns the results of gden() on the appropriate object.


ds2 = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8,2,1,3,2,2,5,2,3,7,2,4,9),ncol=3,byrow=TRUE) #create person period data for two people
colnames(ds2) = c("Id", "Time", "Evt")
ds2 = as.data.frame(ds2)
mcfun <- function(x){
  mc <- markovchainFit(x, name="mc")$estimate
  am <- mc@transitionMatrix
  em <- network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE) #make network object
  gden(em)#calculate density of network, etc
  
}
tapply(ds2$Evt, ds2$Id, mcfun)
#    1    2 
# 0.25 0.25 

Upvotes: 0

Related Questions