从markovchainListFit中的列表中提取矩阵

时间:2016-09-08 18:53:20

标签: r markov-chains

我正在尝试从markovchainListFit中提取矩阵,但我无法提取矩阵。

library(markovchain)
mat <- data.frame(A = c(rep(0, 10)),                                                 
                  B = c(40 ,37, 35 ,30, 27, 21, 15, 16, 21, 19),     
                  C = c(10, 15, 20, 23, 44, 34, 47, 22, 37, 29),  
                  D = c(1, 2, 3, 5, 9, 21, 8, 12, 17, 12))       

mat$A <- apply(mat, 1, function(x) 100 - sum(x))                                     

# Build sequence from mat
tseq <- apply(t(mat), 2, function(x) rep(row.names(t(mat)), x))

# Fit Markov Matrices to sequences
mcListFit <- markovchainListFit(data = tseq)

我尝试了什么:

> mcListFit$estimate[[1]]

Unnamed Markov chain 
 A  4 - dimensional discrete Markov Chain defined by the following states: 
 A, B, C, D 
 The transition matrix  (by rows)  is defined as follows: 
          A          B    C   D
A 0.9387755 0.06122449 0.00 0.0
B 0.0000000 0.85000000 0.15 0.0
C 0.0000000 0.00000000 0.90 0.1
D 0.0000000 0.00000000 0.00 1.0

> as.matrix(mcListFit$estimate[[1]])
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

> as.matrix(unlist(mcListFit$estimate[[1]]))
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

但是我仍然无法提取任何矩阵。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

此代码可以提供帮助:

#allocate a generic list
matrixList<-list()
#sequentially fill the list with the matrices
#using dim method to get the length of the estimates
for (i in 1:dim(mcListFit$estimate)) {
  myMatr<-  mcListFit$estimate[[i]]@transitionMatrix
  matrixList[[i]]<-myMatr
}
matrixList