问题描述
我正在学习如何使用马尔可夫链,但我不断收到错误消息。我想知道是否有人能告诉我我做错了什么。我想分别将 dnormal、rnormal 转换为 dgamma 和 rgamma。感谢您抽出宝贵时间。
pr <- c(0.2,0.7,0.1)
mu <- c(-1,2)
sd <- c(.5,4,2)
p <- function(x)
pr[1] * dgamma(x,mu[1],sd[1]) +
pr[2] * dgamma(x,mu[2],sd[2]) +
pr[3] * dgamma(x,mu[3],sd[3])
q <- function(x) rgamma(1,x,1)
step <- function(x,f,q) {
## Pick new point
xp <- q(x)
## Acceptance probability:
alpha <- min(1,f(xp) / f(x))
## Accept new point with probability alpha:
if (runif(1) < alpha)
x <- xp
## Returning the point:
x
}
mcmc <- function(x,nsteps,q) {
res <- matrix(NA,length(x))
for (i in seq_len(nsteps))
res[i,] <- x <- step(x,q)
drop(res)
}
curve(p(x),col="red",-4,8,n=301,las=1)
#Error in plot.window(...) : need finite 'ylim' values
#In addition: Warning messages:
#1: In dgamma(x,sd[1]) : NaNs produced
#2: In min(x) : no non-missing arguments to min; returning Inf
#3: In max(x) : no non-missing arguments to max; returning -Inf
x11()
res <- mcmc(1,10,p,q)
#Error in if (runif(1) < alpha) x <- xp :
# missing value where TRUE/FALSE needed
编者注:我已经厌倦了尝试对这个冗长且可能无用的控制台输出的其余部分进行所需的手术。
另外:警告消息: 1:在 dgamma(x,sd[1]) 中:产生 NaN 2:在 dgamma(x,sd[1]) 中:产生 NaN
layout(matrix(c(1,2),1,widths=c(4,1)) par(mar=c(4.1,.5,.5),oma=c(0,4.1,0)) plot(res,type="s",xpd=NA,ylab="Parameter",xlab="Sample",las=1) 绘图错误(res,type = "s",xpd = NA,ylab = "Parameter",xlab = "Sample",: 未找到对象“res” usr
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)