# 拓端数据(tecdat):R语言如何使用rjags R2jags来建立贝叶斯模型

## 原文链接：http://tecdat.cn/?p=2857

``read dataseed=read.csv("seeds_dataset.csv")seed=seed[,1:7]查看数据的结构str(seed)'data.frame': 209 obs. of 7 variables: \$ area : num 14.9 14.3 13.8 16.1 14.4 ... \$ perimeter : num 14.6 14.1 13.9 15 14.2 ... \$ campactness : num 0.881 0.905 0.895 0.903 0.895 ... \$ length : num 5.55 5.29 5.32 5.66 5.39 ... \$ width : num 3.33 3.34 3.38 3.56 3.31 ... \$ asymmetry : num 1.02 2.7 2.26 1.35 2.46 ... \$ groovelength: num 4.96 4.83 4.8 5.17 4.96 ...``

``Do a linear modellm(formula = groovelength ~ area + perimeter + campactness, data = seed) Residuals: Min 1Q Median 3Q Max -0.66375 -0.10094 0.00175 0.11081 0.45132 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 19.46173 2.45031 7.943 1.29e-13 *** area 0.49724 0.08721 5.701 4.10e-08 *** perimeter -0.63162 0.18179 -3.474 0.000624 *** campactness -14.05218 1.34325 -10.461 < 2e-16 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 0.1608 on 205 degrees of freedom Multiple R-squared: 0.895, Adjusted R-squared: 0.8934 F-statistic: 582.4 on 3 and 205 DF, p-value: < 2.2e-16``

``Bayesian analysis With bayesglmbayesglm(formula = groovelength ~ area + perimeter + campactness, data = seed) Deviance Residuals: Min 1Q Median 3Q Max -0.66331 -0.09974 -0.00002 0.11110 0.44841 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 18.90538 2.41549 7.827 2.63e-13 *** area 0.47826 0.08604 5.559 8.40e-08 *** perimeter -0.59252 0.17937 -3.303 0.00113 ** campactness -13.74353 1.32463 -10.375 < 2e-16 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 (Dispersion parameter for gaussian family taken to be 0.02584982) Null deviance: 50.4491 on 208 degrees of freedom Residual deviance: 5.2992 on 205 degrees of freedom AIC: -164.91 Number of Fisher Scoring iterations: 6``

``library(coda)建立贝叶斯模型jags(model.file='bayes.bug',parameters=c("area","perimeter","campactness","int"),data =list('a' =seed\$area, 'b' =seed\$perimeter, 'c' =seed\$campactness, 'N'=N, 'y'=groovelength),n.chains =4,inits=NULL)``

``module glm loadedCompiling model graph Resolving undeclared variables Allocating nodes Graph information: Observed stochastic nodes: 209 Unobserved stochastic nodes: 5 Total graph size: 1608Initializing modellibrary('R2jags')bb <-jags1\$BUGSoutput extract the "BUGS output" componentmm <-as.mcmc.bugs(bb) convert it to an "mcmc" object that coda can handleplot(jags1) large-format graph``

trace + density plots, same as above prettier trace plot

prettier density plot

estimate + credible interval plot

180 声望
34 粉丝
0 条评论