我在一栏中有一个文本,我想要建立一个马尔可夫链。我想知道有一种方法可以为状态A,B,C,D建立马尔可夫链,并生成带有这种状态的马尔可夫链。有什么想法吗?
A<- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B')
发布于 2016-12-31 07:21:43
既然您提到您知道如何使用statetable.msm
,下面是一种将数据转换为它可以处理的表单的方法:
dd <- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B')
在破折号上分开并排列成列:
d2 <- data.frame(do.call(cbind,strsplit(dd,"-")))
在数据帧中排列,按顺序标识:
d3 <- tidyr::gather(d2)
构建过渡矩阵:
statetable.msm(value,key,data=d3)
发布于 2016-12-31 07:04:03
如果要从数据中用MLE计算转移概率矩阵(行随机),请尝试如下:
A <- c('A-B-C-D', 'A-B-C-A', 'A-B-A-B', 'D-B-C-A') # the data: by modifying your example data little bit
df <- as.data.frame(do.call(rbind, lapply(strsplit(A, split='-'), function(x) t(sapply(1:(length(x)-1), function(i) c(x[i], x[i+1]))))))
tr.mat <- table(df[,1], df[,2])
tr.mat <- tr.mat / rowSums(tr.mat) # make the matrix row-stochastic
tr.mat
# A B C D
# A 0.0000000 1.0000000 0.0000000 0.0000000 # P(A|A), P(B|A), P(C|A), P(D|A) with MLE from data
# B 0.2500000 0.0000000 0.7500000 0.0000000
# C 0.6666667 0.0000000 0.0000000 0.3333333
# D 0.0000000 1.0000000 0.0000000 0.0000000
https://stackoverflow.com/questions/41409154
复制