20/03/24 11:57:10 TnHQvRcs.net
上記の準備をして以下で実行
PCRj2 <- function(
N,X,
UL=1,
SEN=0.7,
SPC=0.9,
SD=0.05,
print=TRUE){
# UL:upper limit of dunif(0,UL)
library(rjags)
library(BEST)
sn=Mv2ab(SEN,SD^2)
sp=Mv2ab(SPC,SD^2)
modelstring=paste0('
model
{
x ~ dbin(p,n)
p <- prev*sen + (1-prev)*(1-spc)
sen ~ dbeta(sn[1],sn[2])
spc ~ dbeta(sp[1],sp[2])
prev ~ dunif(0,ul)
}
')
writeLines(modelstring,'TEMPmodelj.txt')
dataList=list(n=N,x=X,ul=UL,sen=SEN,spc=SPC,sn=sn,sp=sp)
jagsModel = jags.model( file="TEMPmodelj.txt" ,data=dataList, quiet=TRUE)
update(jagsModel)
codaSamples = coda.samples( jagsModel ,
variable=c("prev","p","sen","spc"), n.iter=1e5, thin=5)
js=as.matrix(codaSamples)
if(print){
BEST::plotPost(js[,'prev'],xlab='prevalence',showMode = TRUE)
lines(density(js[,'prev']),col='skyblue')}
re=c(mean=mean(js[,'prev']),HDInterval::hdi(js[,'prev'])[1:2])
return(re)
}
options(digits = 5)
options(scipen = 5)
PCRj2(1000,10) # 陽性率1%で有病率を推定
PCRj2(1000,300) # 陽性率30%で有病率を推定
PCRj2(1000,600) # 陽性率60%で有病率を推定