使用 R 进行马尔可夫链模拟

markov chain simulation using R

我想绘制不同时间 t 的状态概率分布图。我有转换矩阵

P1 <- matrix(c(0, 1, 0, 0, 0, 0, 2/3, 1/3, 0, 1, 0, 0, 0, 0, 0, 1), 4, 4, byrow=TRUE) 

要绘制从 p1 到 p50 的图形,我使用以下代码。

library(ggplot2)

initState <- c(1,0,0,0) # The initial state will be state 1

# Initiate probability vectors
one <- c()
two <- c()
three <- c()
four <- c()

# Calculate probabilities for 50 steps.
for(k in 1:50){
  nsteps <- initState*P1^k
  one[k] <- nsteps[1,1]
  two[k] <- nsteps[1,2]
  three[k] <- nsteps[1,3]
  four[k] <- nsteps[1,4]
}

# Make dataframes and merge them
one <- as.data.frame(one)
one$Group <- 'one'
one$Iter <- 1:50
names(one)[1] <- 'Value'

two <- as.data.frame(two)
two$Group <- 'two'
two$Iter <- 1:50
names(two)[1] <- 'Value'

three <- as.data.frame(three)
three$Group <- 'three'
three$Iter <- 1:50
names(three)[1] <- 'Value'

four <- as.data.frame(four)
four$Group <- 'four'
four$Iter <- 1:50
names(four)[1] <- 'Value'

steps <- rbind(one,two,three,four)

# Plot the probabilities using ggplot
ggplot(steps, aes(x = Iter, y = Value, col = Group))+
  geom_line() +
  xlab('Chain Step') +
  ylab('Probability') +
  ggtitle('50 Step Chain Probability Prediction')+
  theme(plot.title = element_text(hjust = 0.5))

但是结果很奇怪,谁能找出我的代码哪里出错了?

问题出在你对P1^k的计算上。在 R 中,使用 ^ 逐元素取幂,而不是通过矩阵乘法。要计算 P1 的矩阵幂,您需要将其相乘,或使用 expm 包中的 %^% 运算符。 (在其他包中也可能有此操作的其他实现。)

所以这样写你的循环:

# Calculate probabilities for 50 steps.
P1tok <- diag(4)   # the identity matrix
for(k in 1:50){
  P1tok <- P1tok %*% P1     # multiply by another P1
  nsteps <- initState*P1tok
  one[k] <- nsteps[1,1]
  two[k] <- nsteps[1,2]
  three[k] <- nsteps[1,3]
  four[k] <- nsteps[1,4]
}