I am working on a Gibbs sampler and my code is as follows. The idea is (1)sample pi
first (2) sample delta
(3) sample beta
.
library(foreign)
cognitive `=read.dta("http://www.stat.columbia.edu/~gelman/arm/examples/child.iq/kidiq.dta")`
summary(cognitive)
cognitive$mom_work = as.numeric(cognitive$mom_work > 1)
cognitive$mom_hs = as.numeric(cognitive$mom_hs > 0)
# Modify column names of the data set
colnames(cognitive) = c("kid_score", "hs", "IQ", "work", "age")
x<-cbind(cognitive$hs, cognitive$IQ, cognitive$work, cognitive$age)
y<-cognitive$kid_score
lmmodel<-lm(y~x-1, data=cognitive)
NSim=3000 #iteration
Betahat=solve(t(x)%*%x)%*%t(x)%*%y
Error in if (delta[ite, j] == 1) rnorm(1, mu1, sigma1) else rnorm(1, mu0, : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In rbinom(1, 1, prob = (p1/(p0 + p1))): NAs produced 2: In rbinom(1, 1, prob = (p1/(p0 + p1))): NAs produced
error is caused by the line prob=(pi[ite]*exp(-beta[ite-1,j]^2/(2*10^2)))/(((1-pi[ite])*10^3)*exp(-beta[ite-1,j]^2/(2*10^(-4)))+pi[ite-1]*exp(-beta[ite-1,j]^2/(2*10^2)))
: at some iteration prob
becomes greater than 1, so rbern()
returns NA
. Check your formula.
UPD. For debugging, add the following before your delta[ite,j]=rbern(...
line:
prob_full <- (pi[ite]*exp(-beta[ite-1,j]^2/(2*10^2)))/(((1-pi[ite])*10^3)*exp(-beta[ite-1,j]^2/(2*10^(-4)))+pi[ite-1]*exp(-beta[ite-1,j]^2/(2*10^2)));
cat('\n',ite,j,prob_full)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.