Creating three-state Markov chain plot

。_饼干妹妹 提交于 2020-01-24 09:46:06

问题


I have following dataframe with there states: angry, calm, and tired. The dataframe below provides individual cases of transition of one state into another.

pre<-cbind(c(rep("tired",100),rep("angry",100),rep("calm",100)))
post<-cbind(c(rep("tired",50),rep("angry",70),rep("calm",100),rep("tired",80)))
df<-cbind(pre,post)
df<-as.data.frame(df)
colnames(df)<-c("pre","post")

What I would like to achieve is buidling a Markov's chain plot for three states that is also called "playground" and looks like this:

How would I do it in R?

Thanks in advance!


回答1:


We can use the markovchain package, using the plot method in diagram.

Let's first compute the transition probability matrix from your df

states<-c("tired","angry","calm")

probsCase<-function(i,j){
  sum(as.character(df$pre)==states[i] & as.character(df$post)==states[j])/sum(as.character(df$pre)==states[i])
}

transitionMatrix<-outer(1:3,1:3,Vectorize(probsCase))
colnames(transitionMatrix)<-states
rownames(transitionMatrix)<-states

Now use markovchain to initialize and plot the matrix

library(markovchain)
markovChain <- new("markovchain", states=states, transitionMatrix=transitionMatrix)
plot(markovChain,package="diagram")

EDIT:

If you have troubles installing the markovchain package, we can actually not use it and use directly the diagram package, which needs just transitionMatrix

library(diagram)
plotmat(transitionMatrix,relsize=0.7)

You can then tweak the appearance according to your taste using the options in plotmat



来源:https://stackoverflow.com/questions/36574814/creating-three-state-markov-chain-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!