R(3)中马尔可夫链的人工模拟
我一直在努力提高,这样我就可以合并 源代码R(3)中马尔可夫链的人工模拟,r,statistics,simulation,probability,markov-chains,R,Statistics,Simulation,Probability,Markov Chains,我一直在努力提高,这样我就可以合并 源代码 states <- c(1, 2) alpha <- c(1, 1)/2 mat <- matrix(c(0.5, 0.5, 0, 1), nrow = 2, ncol = 2, byrow = TRUE) # this function calculates the next state, if present state is given. # X = present states # pM
states <- c(1, 2)
alpha <- c(1, 1)/2
mat <- matrix(c(0.5, 0.5,
0, 1), nrow = 2, ncol = 2, byrow = TRUE)
# this function calculates the next state, if present state is given.
# X = present states
# pMat = probability matrix
nextX <- function(X, pMat)
{
#set.seed(1)
probVec <- vector() # initialize vector
if(X == states[1]) # if the present state is 1
{
probVec <- pMat[1,] # take the 1st row
}
if(X==states[2]) # if the prsent state is 2
{
probVec <- pMat[2,] # take the 2nd row
}
return(sample(states, 1, replace=TRUE, prob=probVec)) # calculate the next state
}
# this function simulates 5 steps
steps <- function(alpha1, mat1, n1)
{
vec <- vector(mode="numeric", length = n1+1) # initialize an empty vector
X <- sample(states, 1, replace=TRUE, prob=alpha1) # initial state
vec[1] <- X
for (i in 2:(n1+1))
{
X <- nextX(X, mat1)
vec[i] <- X
}
return (vec)
}
# this function repeats the simulation n1 times.
# steps(alpha1=alpha, mat1=mat, n1=5)
simulate <- function(alpha1, mat1, n1)
{
mattt <- matrix(nrow=n1, ncol=6, byrow=T);
for (i in 1:(n1))
{
temp <- steps(alpha1, mat1, 5)
mattt[i,] <- temp
}
return (mattt)
}
为什么这个源代码给出了NaN
我怎样才能更正它呢?我没有检查您的其余代码,但似乎只有
prob
有错误;你把行和列混在一起了,应该是这样的
prob <- function(simMat, fromStep, toStep, fromState, toState)
mean(simMat[simMat[, fromStep + 1] == fromState, toStep + 1] == toState)
prob0。样本估计也是如此:如果没有X0=1的情况,则prob
内部平均值中的“分母”为零。因此,它不能也不应该被修复(即,在这些情况下返回0是错误的)。我的答案有用吗?@JuliusVainora,我的测试结束了。所以,我没有再去调查。
NaN
prob <- function(simMat, fromStep, toStep, fromState, toState)
mean(simMat[simMat[, fromStep + 1] == fromState, toStep + 1] == toState)