├── 1e
├── ANOVAonewayBRugs.R
├── ANOVAonewayBRugsSTZ.R
├── ANOVAonewayJagsSTZ.R
├── ANOVAonewayNonhomogvarBrugs.R
├── ANOVAonewayNonhomogvarJagsSTZ.R
├── ANOVAtwowayBRugs.R
├── ANOVAtwowayBRugsSTZ.R
├── ANOVAtwowayBRugsWithinSubj.R
├── ANOVAtwowayJagsSTZ.R
├── ANOVAtwowayJagsWithinSubj.R
├── AnovaTwoFactor.R
├── AnovaTwoFactorData.csv
├── BEST.R
├── BEST1G.R
├── BEST1Gexample.R
├── BESTexample.R
├── BESTexamplePower.R
├── BMLR.R
├── BMLRexample.R
├── BMLRexampleData.csv
├── BMLRexampleLargeNdata.csv
├── BayesUpdate.R
├── Bayesian estimation supersedes the t test
│ ├── BEST.pdf
│ ├── Kruschke2012JEPG.pdf
│ ├── README.md
│ └── src
│ │ ├── BEST.R
│ │ ├── BEST1G.R
│ │ ├── BEST1Gexample.R
│ │ ├── BESTexample.R
│ │ ├── BESTexamplePower.R
│ │ ├── HDIofICDF.R
│ │ ├── HDIofMCMC.R
│ │ ├── openGraphSaveGraph.R
│ │ └── plotPost.R
├── BernBeta.R
├── BernBetaBugsFull.R
├── BernBetaJagsFull.R
├── BernBetaModelCompBrugs.R
├── BernBetaModelCompJags.R
├── BernBetaMuKappaBugs.R
├── BernBetaMuKappaJags.R
├── BernGrid.R
├── BernGridExample.R
├── BernMetropolisTemplate.R
├── BernTwoBugs.R
├── BernTwoBugsPriorOnly.R
├── BernTwoFurrowsBugs.R
├── BernTwoGrid.R
├── BernTwoJags.R
├── BernTwoJagsPriorOnly.R
├── BernTwoMetropolis.R
├── BetaPosteriorPredictions.R
├── BinomHierGrid.R
├── BinomHierTwoCoins.R
├── BinomMCMCdemo.R
├── BinomNHSTpoissonrate.R
├── BloodDataGenerator.R
├── DBDA_1stPrintingErrata.pdf
├── Feldman1988Table4data.R
├── FilconBrugs.R
├── FilconBrugsMuKappa.Rdata
├── FilconBrugsPower.R
├── FilconCoKappaBrugs.R
├── FilconCoKappaJags.R
├── FilconJags.R
├── FilconJagsPower.R
├── FilconModelCompBrugs.R
├── FilconModelCompJags.R
├── FilconModelCompPseudoPriorBrugs.R
├── FilconModelCompPseudoPriorJags.R
├── Guber1999data.txt
├── HDIofGrid.R
├── HDIofICDF.R
├── HDIofMCMC.R
├── HtWtDataGenerator.R
├── IncomeFamilySizeState.csv
├── IncomeFamszState.Rdata
├── IntegralOfDensity.R
├── JagsCensoringExample.R
├── Kruschke1996CSdatsum.Rdata
├── Lock1993data.txt
├── LogisticOnewayAnovaBrugs.R
├── LogisticOnewayAnovaHeteroVarBrugs.R
├── LogisticOnewayAnovaJagsSTZ.R
├── MaxwellDelaneyCh12data.csv
├── McDonaldSK1991data.txt
├── McIntyre1994data.csv
├── Moore2006data.txt
├── MultiLinRegressHyperBrugs.R
├── MultiLinRegressHyperJags.R
├── MultiLinRegressInterBrugs.R
├── MultiLinRegressInterJags.R
├── MultipleLinearRegressionBrugs.R
├── MultipleLinearRegressionJags.R
├── MultipleLogisticRegressionBrugs.R
├── MultipleLogisticRegressionJags.R
├── NHSTtwoTierStoppingExercise.R
├── NonhomogVarData.csv
├── NormalModelCompBrugs.R
├── NormalModelCompJags.R
├── OneOddGroupModelComp.R
├── OneOddGroupModelCompJags.R
├── OrdinalProbitDataGenerator.R
├── OrdinalProbitRegressionBrugs.R
├── OrdinalProbitRegressionJags.R
├── PoissonExponentialBrugs.R
├── PoissonExponentialJagsSTZ.R
├── QianS2007SeaweedData.txt
├── RatLives.Rdata
├── RunningProportion.R
├── Salary.csv
├── SimpleGraph.R
├── SimpleLinearRegressionBrugs.R
├── SimpleLinearRegressionJags-Original.R
├── SimpleLinearRegressionJags-WithQuadTrend.R
├── SimpleLinearRegressionJags.R
├── SimpleLinearRegressionRepeatedBrugs.R
├── SimpleLinearRegressionRepeatedJags.R
├── SimpleRobustLinearRegressionBrugs.R
├── SimpleRobustLinearRegressionJags.R
├── SolariLS2008data.txt
├── SolutionsManual_Kruschke_DoingBayesianDataAnalysis.pdf
├── SplitPlotJags.R
├── Systems.Rdata
├── SystemsBrugs.R
├── SystemsJags.R
├── TerrierWeights.csv
├── ToyModelComp.R
├── ToyModelCompJags.R
├── YmetricXsingleBrugs.R
├── YmetricXsingleJags.R
├── minNforHDIpower.R
├── openGraphSaveGraph.R
├── plotChains.R
├── plotPost.R
└── plotPostOLD.R
├── 2e
├── AnovaShrinkageData.csv
├── BattingAverage.csv
├── BernBeta.R
├── BernBetaExample.R
├── BernGrid.R
├── BernGridExample.R
├── BernMetrop.R
├── BugsRatsData.csv
├── CondLogistRegData1.csv
├── CondLogistRegData2.csv
├── CrimeDrink.csv
├── DBDA2E-utilities.R
├── ExamplesOfR.R
├── FourByFourCount.csv
├── FruitflyDataReduced.csv
├── Guber1999data.csv
├── HGN.csv
├── HairEyeColor.csv
├── HappinessAssetsDebt.csv
├── HierLinRegressData.csv
├── HtWtData110.csv
├── HtWtData30.csv
├── HtWtData300.csv
├── HtWtDataGenerator.R
├── IncomeFamszState.csv
├── IncomeFamszState3yr.csv
├── IntegralOfDensity.R
├── ItemResponseTheoryData.csv
├── Jags-BivariateNormalScript.R
├── Jags-ExampleScript.R
├── Jags-ItemResponseTheoryScript.R
├── Jags-MetaAnalysisBetaBlockers.R
├── Jags-Ybinom-Xnom1fac-Mlogistic-Example.R
├── Jags-Ybinom-Xnom1fac-Mlogistic.R
├── Jags-Ybinom-XnomSsubjCcat-MbinomBetaOmegaKappa-Example.R
├── Jags-Ybinom-XnomSsubjCcat-MbinomBetaOmegaKappa.R
├── Jags-Ycount-Xnom2fac-MpoissonExp-Example.R
├── Jags-Ycount-Xnom2fac-MpoissonExp.R
├── Jags-Ydich-XmetMulti-Mlogistic-Example.R
├── Jags-Ydich-XmetMulti-Mlogistic.R
├── Jags-Ydich-XmetMulti-MlogisticRobust-Example.R
├── Jags-Ydich-XmetMulti-MlogisticRobust.R
├── Jags-Ydich-Xnom1subj-MbernBeta-Example.R
├── Jags-Ydich-Xnom1subj-MbernBeta-Power.R
├── Jags-Ydich-Xnom1subj-MbernBeta.R
├── Jags-Ydich-Xnom1subj-MbernBetaModelComp.R
├── Jags-Ydich-Xnom1subj-MbernBetaModelCompPseudoPrior.R
├── Jags-Ydich-XnomSsubj-MbernBeta-Example.R
├── Jags-Ydich-XnomSsubj-MbernBeta.R
├── Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa-Example.R
├── Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa.R
├── Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa-Example.R
├── Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa-Power.R
├── Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa.R
├── Jags-Ymet-Xmet-Mrobust-Example.R
├── Jags-Ymet-Xmet-Mrobust.R
├── Jags-Ymet-XmetMulti-Mrobust-Example.R
├── Jags-Ymet-XmetMulti-Mrobust.R
├── Jags-Ymet-XmetMulti-MrobustShrink-Example.R
├── Jags-Ymet-XmetMulti-MrobustShrink.R
├── Jags-Ymet-XmetMulti-MrobustVarSelect-Example.R
├── Jags-Ymet-XmetMulti-MrobustVarSelect.R
├── Jags-Ymet-XmetSsubj-MrobustHier-Example.R
├── Jags-Ymet-XmetSsubj-MrobustHier.R
├── Jags-Ymet-XmetSsubj-MrobustHierQuadWt-Example.R
├── Jags-Ymet-XmetSsubj-MrobustHierQuadWt.R
├── Jags-Ymet-Xnom1fac-MnormalHom-Example.R
├── Jags-Ymet-Xnom1fac-MnormalHom.R
├── Jags-Ymet-Xnom1fac-MrobustHet-Example.R
├── Jags-Ymet-Xnom1fac-MrobustHet.R
├── Jags-Ymet-Xnom1grp-Mnormal-Example.R
├── Jags-Ymet-Xnom1grp-Mnormal.R
├── Jags-Ymet-Xnom1grp-Mrobust-Example.R
├── Jags-Ymet-Xnom1grp-Mrobust.R
├── Jags-Ymet-Xnom1met1-MnormalHom-Example.R
├── Jags-Ymet-Xnom1met1-MnormalHom.R
├── Jags-Ymet-Xnom2fac-MnormalHom-Example.R
├── Jags-Ymet-Xnom2fac-MnormalHom.R
├── Jags-Ymet-Xnom2fac-MrobustHet-Example.R
├── Jags-Ymet-Xnom2fac-MrobustHet.R
├── Jags-Ymet-Xnom2grp-MrobustHet-Example.R
├── Jags-Ymet-Xnom2grp-MrobustHet.R
├── Jags-Ymet-XnomSplitPlot-MnormalHom-Example.R
├── Jags-Ymet-XnomSplitPlot-MnormalHom.R
├── Jags-YmetBinned-Xnom1grp-MnormalInterval-Example.R
├── Jags-YmetBinned-Xnom1grp-MnormalInterval.R
├── Jags-YmetCensored-Xnom2grp-Mweibull.R
├── Jags-Ynom-XmetMulti-McondLogistic1-Example.R
├── Jags-Ynom-XmetMulti-McondLogistic1.R
├── Jags-Ynom-XmetMulti-McondLogistic2-Example.R
├── Jags-Ynom-XmetMulti-McondLogistic2.R
├── Jags-Ynom-XmetMulti-Msoftmax-Example.R
├── Jags-Ynom-XmetMulti-Msoftmax.R
├── Jags-Yord-XmetMulti-Mnormal-Example.R
├── Jags-Yord-XmetMulti-Mnormal.R
├── Jags-Yord-Xnom1grp-Mnormal-Example.R
├── Jags-Yord-Xnom1grp-Mnormal.R
├── Jags-Yord-Xnom2grp-MnormalHet-Example.R
├── Jags-Yord-Xnom2grp-MnormalHet.R
├── Kruschke-DBDA2E-ExerciseSolutions.pdf
├── Kruschke-DoingBayesian2ndEd-Figures.pdf
├── MetaAnalysisBetaBlocker.csv
├── Movies.csv
├── MultLinRegrPlotCorr.csv
├── MultLinRegrPlotUnif.csv
├── NonhomogVarData.csv
├── OneOddGroupModelComp2E.R
├── OrdinalProbitData-1grp-1.csv
├── OrdinalProbitData-1grp-2.csv
├── OrdinalProbitData-LinReg-2.csv
├── OrdinalProbitData-Movies.csv
├── OrdinalProbitData1.csv
├── RatLives.csv
├── RunningProportion.R
├── Salary.csv
├── SeaweedData.csv
├── ShohatOphirKAMH2012dataReduced.csv
├── SimpleGraph.R
├── SoftmaxRegData1.csv
├── SoftmaxRegData2.csv
├── SplitPlotAgriData.csv
├── Stan-BernBeta-Script.R
├── Stan-Ydich-Xnom1subj-MbernBeta-Example.R
├── Stan-Ydich-Xnom1subj-MbernBeta.R
├── Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa-Example.R
├── Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa.R
├── Stan-Ymet-Xmet-Mrobust-Example.R
├── Stan-Ymet-Xmet-Mrobust.R
├── Stan-Ymet-XmetSsubj-MrobustHierQuadWt-Example.R
├── Stan-Ymet-XmetSsubj-MrobustHierQuadWt.R
├── Stan-Ymet-Xnom1grp-Mrobust-Example.R
├── Stan-Ymet-Xnom1grp-Mrobust.R
├── Stan-Ymet-Xnom2grp-MrobustHet-Example.R
├── Stan-Ymet-Xnom2grp-MrobustHet.R
├── TherapeuticTouchData.csv
├── TwoGroupIQ.csv
├── minNforHDIpower-example.R
├── minNforHDIpower.R
├── z15N50.csv
└── z6N8z2N7.csv
└── README.md
/1e/BEST1Gexample.R:
--------------------------------------------------------------------------------
1 |
2 | # OPTIONAL: Clear R's memory and graphics:
3 | rm(list=ls()) # Careful! This clears all of R's memory!
4 | graphics.off() # This closes all of R's graphics windows.
5 |
6 | # Specify the data
7 | y = c(101,100,102,104,102,97,105,105,98,101,100,123,105,103,100,95,102,106,
8 | 109,102,82,102,100,102,102,101,102,102,103,103,97,97,103,101,97,104,
9 | 96,103,124,101,101,100,101,101,104,100,101)
10 |
11 | # Run the Bayesian analysis:
12 | source("BEST1G.R")
13 | mcmcChain = BEST1Gmcmc( y )
14 |
15 | # Display the results:
16 | BEST1Gplot( y , mcmcChain , compValm=100 , ROPEeff=c(-0.1,0.1) , pairsPlot=TRUE )
17 |
--------------------------------------------------------------------------------
/1e/BESTexamplePower.R:
--------------------------------------------------------------------------------
1 | # Version of May 26, 2012.
2 | # John K. Kruschke
3 | # johnkruschke@gmail.com
4 | # http://www.indiana.edu/~kruschke/BEST/
5 | #
6 | # This program is believed to be free of errors, but it comes with no guarantee!
7 | # The user bears all responsibility for interpreting the results.
8 | # Please check the webpage above for updates or corrections.
9 | #
10 | ### ***************************************************************
11 | ### ******** SEE FILE BESTexample.R FOR INSTRUCTIONS **************
12 | ### ***************************************************************
13 |
14 | # OPTIONAL: Clear R's memory and graphics:
15 | rm(list=ls()) # Careful! This clears all of R's memory!
16 | graphics.off() # This closes all of R's graphics windows.
17 |
18 | # Get the functions loaded into R's working memory:
19 | source("BEST.R")
20 |
21 | #-------------------------------------------------------------------------------
22 | # RETROSPECTIVE POWER ANALYSIS.
23 | # !! This section assumes you have already run BESTexample.R !!
24 | # Re-load the saved data and MCMC chain from the previously conducted
25 | # Bayesian analysis. This re-loads the variables y1, y2, mcmcChain, etc.
26 | load( "BESTexampleMCMC.Rdata" )
27 | power = BESTpower( mcmcChain , N1=length(y1) , N2=length(y2) ,
28 | ROPEm=c(-0.1,0.1) , ROPEsd=c(-0.1,0.1) , ROPEeff=c(-0.1,0.1) ,
29 | maxHDIWm=2.0 , maxHDIWsd=2.0 , maxHDIWeff=0.2 , nRep=1000 ,
30 | mcmcLength=10000 , saveName = "BESTexampleRetroPower.Rdata" )
31 |
32 | #-------------------------------------------------------------------------------
33 | # PROSPECTIVE POWER ANALYSIS, using fictitious strong data.
34 | # Generate large fictitious data set that expresses hypothesis:
35 | prospectData = makeData( mu1=108, sd1=17, mu2=100, sd2=15, nPerGrp=1000,
36 | pcntOut=10, sdOutMult=2.0, rnd.seed=NULL )
37 | y1pro = prospectData$y1 # Merely renames simulated data for convenience below.
38 | y2pro = prospectData$y2 # Merely renames simulated data for convenience below.
39 | # Generate Bayesian posterior distribution from fictitious data:
40 | # (uses fewer than usual MCMC steps because it only needs nRep credible
41 | # parameter combinations, not a high-resolution representation)
42 | mcmcChainPro = BESTmcmc( y1pro , y2pro , numSavedSteps=2000 )
43 | postInfoPro = BESTplot( y1pro , y2pro , mcmcChainPro , pairsPlot=TRUE )
44 | save( y1pro, y2pro, mcmcChainPro, postInfoPro,
45 | file="BESTexampleProPowerMCMC.Rdata" )
46 | # Now compute the prospective power for planned sample sizes:
47 | N1plan = N2plan = 50 # specify planned sample size
48 | powerPro = BESTpower( mcmcChainPro , N1=N1plan , N2=N2plan , showFirstNrep=5 ,
49 | ROPEm=c(-1.5,1.5) , ROPEsd=c(-0.0,0.0) , ROPEeff=c(-0.0,0.0) ,
50 | maxHDIWm=15.0 , maxHDIWsd=10.0 , maxHDIWeff=1.0 , nRep=1000 ,
51 | mcmcLength=10000 , saveName = "BESTexampleProPower.Rdata" )
52 |
53 | #-------------------------------------------------------------------------------
54 |
--------------------------------------------------------------------------------
/1e/BMLRexample.R:
--------------------------------------------------------------------------------
1 | graphics.off() # Clears all graphical displays.
2 | rm(list=ls(all=TRUE)) # Removes all variables from memory!
3 |
4 | # Get the Bayesian functions into R's working memory:
5 | source("BMLR.R")
6 |
7 | # Load the data into R:
8 | dataMat = read.csv( file="BMLRexampleData.csv" )
9 | # Important: The matrix dataMat must have the criterion y in its first column,
10 | # and the predictors in the subsequent columns!
11 |
12 | # Run the Bayesian analysis and put the results in variable named mcmcChain:
13 | mcmcChain = BMLRmcmc( dataMat )
14 |
15 | # Plot the posterior distribution and put summary in variable named postInfo:
16 | postInfo = BMLRplot( mcmcChain )
17 | # Display the summary on the console:
18 | show(postInfo)
19 |
20 |
21 | # Another example, using a large N data set:
22 | dataMat = read.csv( file="BMLRexampleLargeNdata.csv" )
23 | mcmcChain = BMLRmcmc( dataMat , numSavedSteps=100000 )
24 | postInfo = BMLRplot( mcmcChain ,
25 | ROPEbeta=c(-0.05,0.05) , ROPEbetaDiff=c(-0.05,0.05) )
26 | show(postInfo)
27 |
--------------------------------------------------------------------------------
/1e/BayesUpdate.R:
--------------------------------------------------------------------------------
1 | # Theta is the vector of candidate values for the parameter theta.
2 | # nThetaVals is the number of candidate theta values.
3 | # To produce the examples in the book, set nThetaVals to either 3 or 63.
4 | nThetaVals = 3
5 | # Now make the vector of theta values:
6 | Theta = seq( from = 1/(nThetaVals+1) , to = nThetaVals/(nThetaVals+1) ,
7 | by = 1/(nThetaVals+1) )
8 |
9 | # pTheta is the vector of prior probabilities on the theta values.
10 | pTheta = pmin( Theta , 1-Theta ) # Makes a triangular belief distribution.
11 | pTheta = pTheta / sum( pTheta ) # Makes sure that beliefs sum to 1.
12 |
13 | # Specify the data. To produce the examples in the book, use either
14 | # Data = c(rep(1,3),rep(0,9)) or Data = c(rep(1,1),rep(0,11)).
15 | Data = c(rep(1,3),rep(0,9))
16 | nHeads = sum( Data )
17 | nTails = length( Data ) - nHeads
18 |
19 | # Compute the likelihood of the data for each value of theta:
20 | pDataGivenTheta = Theta^nHeads * (1-Theta)^nTails
21 |
22 | # Compute the posterior:
23 | pData = sum( pDataGivenTheta * pTheta )
24 | pThetaGivenData = pDataGivenTheta * pTheta / pData # This is Bayes' rule!
25 |
26 | # Plot the results.
27 | source("openGraphSaveGraph.R") # read in graph functions
28 | openGraph(width=7,height=10,mag=0.7) # open a window for the graph
29 | layout( matrix( c( 1,2,3 ) ,nrow=3 ,ncol=1 ,byrow=FALSE ) ) # 3x1 panels
30 | par(mar=c(3,3,1,0)) # number of margin lines: bottom,left,top,right
31 | par(mgp=c(2,1,0)) # which margin lines to use for labels
32 | par(mai=c(0.5,0.5,0.3,0.1)) # margin size in inches: bottom,left,top,right
33 |
34 | # Plot the prior:
35 | plot( Theta , pTheta , type="h" , lwd=3 , main="Prior" ,
36 | xlim=c(0,1) , xlab=bquote(theta) ,
37 | ylim=c(0,1.1*max(pThetaGivenData)) , ylab=bquote(p(theta)) ,
38 | cex.axis=1.2 , cex.lab=1.5 , cex.main=1.5 , col="skyblue" )
39 |
40 | # Plot the likelihood:
41 | plot( Theta , pDataGivenTheta , type="h" , lwd=3 , main="Likelihood" ,
42 | xlim=c(0,1) , xlab=bquote(theta) ,
43 | ylim=c(0,1.1*max(pDataGivenTheta)) , ylab=bquote(paste("p(D|",theta,")")),
44 | cex.axis=1.2 , cex.lab=1.5 , cex.main=1.5 , col="skyblue" )
45 | text( .55 , .85*max(pDataGivenTheta) , cex=2.0 ,
46 | bquote( "D=" * .(nHeads) * "H," * .(nTails) * "T" ) , adj=c(0,.5) )
47 |
48 | # Plot the posterior:
49 | plot( Theta , pThetaGivenData , type="h" , lwd=3 , main="Posterior" ,
50 | xlim=c(0,1) , xlab=bquote(theta) ,
51 | ylim=c(0,1.1*max(pThetaGivenData)) , ylab=bquote(paste("p(",theta,"|D)")),
52 | cex.axis=1.2 , cex.lab=1.5 , cex.main=1.5 , col="skyblue" )
53 | text( .55 , .85*max(pThetaGivenData) , cex=2.0 ,
54 | bquote( "p(D)=" * .(signif(pData,3)) ) , adj=c(0,.5) )
55 |
56 | # Save the plot
57 | if ( nThetaVals == 3 ) { modeltype = "simpleModel" }
58 | if ( nThetaVals == 63 ) { modeltype = "complexModel" }
59 | if ( nHeads == 3 & nTails == 9 ) { datatype = "simpleData" }
60 | if ( nHeads == 1 & nTails == 11 ) { datatype = "complexData" }
61 | filename = paste( "BayesUpdate_" ,modeltype ,"_" ,datatype,sep="" )
62 | saveGraph( file=filename , type="eps" )
63 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/BEST.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/Bayesian estimation supersedes the t test/BEST.pdf
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/Kruschke2012JEPG.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/Bayesian estimation supersedes the t test/Kruschke2012JEPG.pdf
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/README.md:
--------------------------------------------------------------------------------
1 | [Bayesian estimation supersedes the *t* test.](http://www.indiana.edu/~kruschke/BEST/)
2 | ====================
3 |
4 | [**John K. Kruschke**](http://www.indiana.edu/~kruschke/)
5 |
6 | ***Journal of Experimental Psychology: General***
7 |
8 | *Abstract*: Bayesian estimation for two groups provides complete distributions of credible values for the effect size, group means and their difference, standard deviations and their difference, and the normality of the data. The method handles outliers. The decision rule can accept the null value (unlike traditional *t* tests) when certainty in the estimate is high (unlike Bayesian model comparison using Bayes factors). The method also yields precise estimates of statistical power for various research goals. The software and programs are free, and run on Macintosh, Linux, and Windows platforms.
9 |
10 | Get the *article* [here](http://www.indiana.edu/~kruschke/articles/Kruschke2012JEPG.pdf). Get the published version here: [doi: 10.1037/a0029146](http://dx.doi.org/10.1037/a0029146).
11 |
12 | There is (as of January 3, 2013) a [web app](http://www.sumsar.net/best_online/) created by [Rasmus Bååth](http://www.sumsar.net/) that provides the primary results of BEST without any need to install software. Just paste in your data and click a button. See the [blog post](http://doingbayesiandataanalysis.blogspot.com/2013/01/bayesian-estimation-in-new-web-app.html).
13 |
14 | Get the *programs* from this [zip file](http://www.indiana.edu/~kruschke/BEST/BEST.zip). *Updated January 23, 2013*. Be sure to unzip (extract) the zip file after it is saved on you computer. For information about *running the programs*, see the comments at the top of the file BESTexample.R.
15 |
16 |
17 | *New (Sept. 3, 2012):* The programs now include a version for estimating the parameters of a single group. The 1-group version is named BEST1G.R. See the example in BEST1Gexample.R and [this blog post](http://doingbayesiandataanalysis.blogspot.com/2012/09/one-group-version-of-best-bayesian.html).
18 |
19 | For information about *installing the software* (R, JAGS, rjags, and RStudio), see the comments at the top of the file BESTexample.R, or at [this blog post](http://doingbayesiandataanalysis.blogspot.com/2012/01/complete-steps-for-installing-software.html).
20 |
21 | You can make comments at [the blog](http://doingbayesiandataanalysis.blogspot.com/). Search the blog with the phrase "Bayesian estimation".
22 |
23 | For a complete tutorial about Bayesian methods, see [the book](http://www.indiana.edu/~kruschke/DoingBayesianDataAnalysis/).
24 |
25 | 
26 | 
27 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/src/BEST1Gexample.R:
--------------------------------------------------------------------------------
1 |
2 | # OPTIONAL: Clear R's memory and graphics:
3 | rm(list=ls()) # Careful! This clears all of R's memory!
4 | graphics.off() # This closes all of R's graphics windows.
5 |
6 | # Specify the data
7 | y = c(101,100,102,104,102,97,105,105,98,101,100,123,105,103,100,95,102,106,
8 | 109,102,82,102,100,102,102,101,102,102,103,103,97,97,103,101,97,104,
9 | 96,103,124,101,101,100,101,101,104,100,101)
10 |
11 | # Run the Bayesian analysis:
12 | source("BEST1G.R")
13 | mcmcChain = BEST1Gmcmc( y )
14 |
15 | # Display the results:
16 | BEST1Gplot( y , mcmcChain , compValm=100 , ROPEeff=c(-0.1,0.1) , pairsPlot=TRUE )
17 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/src/BESTexamplePower.R:
--------------------------------------------------------------------------------
1 | # Version of May 26, 2012.
2 | # John K. Kruschke
3 | # johnkruschke@gmail.com
4 | # http://www.indiana.edu/~kruschke/BEST/
5 | #
6 | # This program is believed to be free of errors, but it comes with no guarantee!
7 | # The user bears all responsibility for interpreting the results.
8 | # Please check the webpage above for updates or corrections.
9 | #
10 | ### ***************************************************************
11 | ### ******** SEE FILE BESTexample.R FOR INSTRUCTIONS **************
12 | ### ***************************************************************
13 |
14 | # OPTIONAL: Clear R's memory and graphics:
15 | rm(list=ls()) # Careful! This clears all of R's memory!
16 | graphics.off() # This closes all of R's graphics windows.
17 |
18 | # Get the functions loaded into R's working memory:
19 | source("BEST.R")
20 |
21 | #-------------------------------------------------------------------------------
22 | # RETROSPECTIVE POWER ANALYSIS.
23 | # !! This section assumes you have already run BESTexample.R !!
24 | # Re-load the saved data and MCMC chain from the previously conducted
25 | # Bayesian analysis. This re-loads the variables y1, y2, mcmcChain, etc.
26 | load( "BESTexampleMCMC.Rdata" )
27 | power = BESTpower( mcmcChain , N1=length(y1) , N2=length(y2) ,
28 | ROPEm=c(-0.1,0.1) , ROPEsd=c(-0.1,0.1) , ROPEeff=c(-0.1,0.1) ,
29 | maxHDIWm=2.0 , maxHDIWsd=2.0 , maxHDIWeff=0.2 , nRep=1000 ,
30 | mcmcLength=10000 , saveName = "BESTexampleRetroPower.Rdata" )
31 |
32 | #-------------------------------------------------------------------------------
33 | # PROSPECTIVE POWER ANALYSIS, using fictitious strong data.
34 | # Generate large fictitious data set that expresses hypothesis:
35 | prospectData = makeData( mu1=108, sd1=17, mu2=100, sd2=15, nPerGrp=1000,
36 | pcntOut=10, sdOutMult=2.0, rnd.seed=NULL )
37 | y1pro = prospectData$y1 # Merely renames simulated data for convenience below.
38 | y2pro = prospectData$y2 # Merely renames simulated data for convenience below.
39 | # Generate Bayesian posterior distribution from fictitious data:
40 | # (uses fewer than usual MCMC steps because it only needs nRep credible
41 | # parameter combinations, not a high-resolution representation)
42 | mcmcChainPro = BESTmcmc( y1pro , y2pro , numSavedSteps=2000 )
43 | postInfoPro = BESTplot( y1pro , y2pro , mcmcChainPro , pairsPlot=TRUE )
44 | save( y1pro, y2pro, mcmcChainPro, postInfoPro,
45 | file="BESTexampleProPowerMCMC.Rdata" )
46 | # Now compute the prospective power for planned sample sizes:
47 | N1plan = N2plan = 50 # specify planned sample size
48 | powerPro = BESTpower( mcmcChainPro , N1=N1plan , N2=N2plan , showFirstNrep=5 ,
49 | ROPEm=c(-1.5,1.5) , ROPEsd=c(-0.0,0.0) , ROPEeff=c(-0.0,0.0) ,
50 | maxHDIWm=15.0 , maxHDIWsd=10.0 , maxHDIWeff=1.0 , nRep=1000 ,
51 | mcmcLength=10000 , saveName = "BESTexampleProPower.Rdata" )
52 |
53 | #-------------------------------------------------------------------------------
54 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/src/HDIofICDF.R:
--------------------------------------------------------------------------------
1 | HDIofICDF = function( ICDFname , credMass=0.95 , tol=1e-8 , ... ) {
2 | # Arguments:
3 | # ICDFname is R's name for the inverse cumulative density function
4 | # of the distribution.
5 | # credMass is the desired mass of the HDI region.
6 | # tol is passed to R's optimize function.
7 | # Return value:
8 | # Highest density iterval (HDI) limits in a vector.
9 | # Example of use: For determining HDI of a beta(30,12) distribution, type
10 | # HDIofICDF( qbeta , shape1 = 30 , shape2 = 12 )
11 | # Notice that the parameters of the ICDFname must be explicitly named;
12 | # e.g., HDIofICDF( qbeta , 30 , 12 ) does not work.
13 | # Adapted and corrected from Greg Snow's TeachingDemos package.
14 | incredMass = 1.0 - credMass
15 | intervalWidth = function( lowTailPr , ICDFname , credMass , ... ) {
16 | ICDFname( credMass + lowTailPr , ... ) - ICDFname( lowTailPr , ... )
17 | }
18 | optInfo = optimize( intervalWidth , c( 0 , incredMass ) , ICDFname=ICDFname ,
19 | credMass=credMass , tol=tol , ... )
20 | HDIlowTailPr = optInfo$minimum
21 | return( c( ICDFname( HDIlowTailPr , ... ) ,
22 | ICDFname( credMass + HDIlowTailPr , ... ) ) )
23 | } # Kruschke, J. K. (2011). Doing Bayesian data analysis: A
24 | # Tutorial with R and BUGS. Elsevier Science/Academic Press.
25 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/src/HDIofMCMC.R:
--------------------------------------------------------------------------------
1 | HDIofMCMC = function( sampleVec , credMass=0.95 ) {
2 | # Computes highest density interval from a sample of representative values,
3 | # estimated as shortest credible interval.
4 | # Arguments:
5 | # sampleVec
6 | # is a vector of representative values from a probability distribution.
7 | # credMass
8 | # is a scalar between 0 and 1, indicating the mass within the credible
9 | # interval that is to be estimated.
10 | # Value:
11 | # HDIlim is a vector containing the limits of the HDI
12 | sortedPts = sort( sampleVec )
13 | ciIdxInc = floor( credMass * length( sortedPts ) )
14 | nCIs = length( sortedPts ) - ciIdxInc
15 | ciWidth = rep( 0 , nCIs )
16 | for ( i in 1:nCIs ) {
17 | ciWidth[ i ] = sortedPts[ i + ciIdxInc ] - sortedPts[ i ]
18 | }
19 | HDImin = sortedPts[ which.min( ciWidth ) ]
20 | HDImax = sortedPts[ which.min( ciWidth ) + ciIdxInc ]
21 | HDIlim = c( HDImin , HDImax )
22 | return( HDIlim )
23 | }
24 |
--------------------------------------------------------------------------------
/1e/Bayesian estimation supersedes the t test/src/openGraphSaveGraph.R:
--------------------------------------------------------------------------------
1 | # openGraphSaveGraph.R
2 | # John K. Kruschke, 2013
3 |
4 | openGraph = function( width=7 , height=7 , mag=1.0 , ... ) {
5 | if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
6 | X11( width=width*mag , height=height*mag , type="cairo" , ... )
7 | } else { # Windows OS
8 | windows( width=width*mag , height=height*mag , ... )
9 | }
10 | }
11 |
12 | saveGraph = function( file="saveGraphOutput" , type="pdf" , ... ) {
13 | if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
14 | if ( any( type == c("png","jpeg","jpg","tiff","bmp")) ) {
15 | sptype = type
16 | if ( type == "jpg" ) { sptype = "jpeg" }
17 | savePlot( file=paste(file,".",type,sep="") , type=sptype , ... )
18 | }
19 | if ( type == "pdf" ) {
20 | dev.copy2pdf(file=paste(file,".",type,sep="") , ... )
21 | }
22 | if ( type == "eps" ) {
23 | dev.copy2eps(file=paste(file,".",type,sep="") , ... )
24 | }
25 | } else { # Windows OS
26 | savePlot( file=file , type=type , ... )
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/1e/BernBetaModelCompBrugs.R:
--------------------------------------------------------------------------------
1 | library(BRugs) # Kruschke, J. K. (2010). Doing Bayesian data analysis:
2 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
3 | #------------------------------------------------------------------------------
4 | # THE MODEL.
5 |
6 | modelstring = "
7 | # BUGS model specification begins here...
8 | model {
9 | # Likelihood:
10 | for ( i in 1:nflips ) {
11 | y[i] ~ dbern( theta ) # y[i] distributed as Bernoulli
12 | }
13 | # Prior distribution:
14 | theta ~ dbeta( aTheta , bTheta ) # theta distributed as beta density
15 | aTheta <- muTheta * kappaTheta
16 | bTheta <- (1-muTheta) * kappaTheta
17 | # Hyperprior:
18 | muTheta <- muThetaModel[ modelIndex ]
19 | muThetaModel[1] <- .75
20 | muThetaModel[2] <- .25
21 | kappaTheta <- 12
22 | # Hyperhyperprior:
23 | modelIndex ~ dcat( modelProb[] )
24 | modelProb[1] <- .5
25 | modelProb[2] <- .5
26 | }
27 | # ... end BUGS model specification
28 | " # close quote for modelstring
29 | # Write model to a file:
30 | .temp = file("model.txt","w") ; writeLines(modelstring,con=.temp) ; close(.temp)
31 | # Load model file into BRugs and check its syntax:
32 | modelCheck( "model.txt" )
33 |
34 | #------------------------------------------------------------------------------
35 | # THE DATA.
36 |
37 | # Specify the data in a form that is compatible with BRugs model, as a list:
38 | y = c( rep(0,3) , rep(1,6) )
39 | nflips = length( y )
40 | datalist = list(
41 | nflips = nflips ,
42 | y = y
43 | )
44 |
45 | # Get the data into BRugs:
46 | # Function bugsData stores the data file (default filename is data.txt).
47 | # Function modelData loads data file into BRugs (default filename is data.txt).
48 | modelData( bugsData( datalist ) )
49 |
50 | #------------------------------------------------------------------------------
51 | # INTIALIZE THE CHAINS.
52 |
53 | modelCompile( numChains=1 )
54 | modelGenInits()
55 |
56 | #------------------------------------------------------------------------------
57 | # RUN THE CHAINS.
58 |
59 | burninSteps = 10000
60 | modelUpdate( burninSteps )
61 | samplesSet( c("theta","modelIndex") )
62 | nPerChain = 100000
63 | modelUpdate( nPerChain , thin=1 ) # takes nPerChain * thin steps
64 |
65 | #------------------------------------------------------------------------------
66 | # EXAMINE THE RESULTS.
67 |
68 | # Get the posterior sample of modelIndex:
69 | modelIdxSample = samplesSample( "modelIndex" )
70 | # Compute the proportion of modelIndex at each value:
71 | pM1 = sum( modelIdxSample == 1 ) / length( modelIdxSample )
72 | pM2 = 1 - pM1
73 |
74 | # Get the posterior sample of theta:
75 | thetaSample = samplesSample( "theta" )
76 | # Extract theta values when modelIndex is 1:
77 | thetaSampleM1 = thetaSample[ modelIdxSample == 1 ]
78 | # Extract theta values when modelIndex is 2:
79 | thetaSampleM2 = thetaSample[ modelIdxSample == 2 ]
80 |
81 | # Plot histograms of sampled theta values for each model,
82 | # with pM displayed.
83 | windows()
84 | layout( matrix(1:2,nrow=2) )
85 | hist( thetaSampleM1 , main="Posterior Theta_1 when Model Index = 1" ,
86 | xlab=expression(theta) , xlim=c(0,1) ,
87 | col="grey" , border="white" )
88 | text( 0 , 0 , bquote( "p(M1|D)" == .(signif(pM1,3)) ) , adj=c(0,-2) , cex=1.5 )
89 | hist( thetaSampleM2 , main="Posterior Theta_2 when Model Index = 2" ,
90 | xlab=expression(theta) , xlim=c(0,1) ,
91 | col="grey" , border="white" )
92 | text( 0 , 0 , bquote( "p(M2|D)" == .(signif(pM2,3)) ) , adj=c(0,-2) , cex=1.5 )
93 |
94 | dev.copy2eps(file="BernBetaModelCompBrugs.eps")
--------------------------------------------------------------------------------
/1e/BernGridExample.R:
--------------------------------------------------------------------------------
1 | graphics.off()
2 | source("openGraphSaveGraph.R") # for openGraph() function, used below.
3 | source("BernGrid.R")
4 |
5 | # For Figure 6.4:
6 | # Specify theta values.
7 | thetagrid = seq(0,1,length=1001)
8 | # Specify probability mass at each theta value.
9 | relprob = sin( 2*pi*thetagrid )^6
10 | prior = relprob / sum(relprob) # probability mass at each theta
11 | # Specify the data vector.
12 | datavec = c( rep(1,2) , rep(0,1) )
13 | # Open a window.
14 | openGraph(width=7,height=10,mag=0.7)
15 | # Call the function.
16 | posterior = BernGrid( Theta=thetagrid , pTheta=prior , Data=datavec )
17 | saveGraph(file="Fig.6.4",type="jpg")
18 |
19 | # For Figure 6.5:
20 | pTheta = c( 50:1 , rep(1,50) , 1:50 , 50:1 , rep(1,50) , 1:50 )
21 | pTheta = pTheta / sum( pTheta )
22 | width = 1 / length(pTheta)
23 | Theta = seq( from = width/2 , to = 1-width/2 , by = width )
24 | dataVec = c( rep(1,3) , rep(0,1) )
25 | openGraph(width=7,height=10,mag=0.7)
26 | posterior = BernGrid( Theta=Theta , pTheta=pTheta , Data=dataVec )
27 | saveGraph(file="Fig.6.5left",type="jpg")
28 | dataVec = c( rep(1,12) , rep(0,4) )
29 | openGraph(width=7,height=10,mag=0.7)
30 | posterior = BernGrid( Theta=Theta , pTheta=posterior , Data=dataVec )
31 | saveGraph(file="Fig.6.5right",type="jpg")
32 |
--------------------------------------------------------------------------------
/1e/BernTwoBugsPriorOnly.R:
--------------------------------------------------------------------------------
1 | library(BRugs) # Kruschke, J. K. (2010). Doing Bayesian data analysis:
2 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
3 | #------------------------------------------------------------------------------
4 | # THE MODEL.
5 |
6 | modelstring = "
7 | # BUGS model specification begins here...
8 | model {
9 | # Likelihood. Each flip is Bernoulli.
10 | for ( i in 1 : N1 ) { y1[i] ~ dbern( theta1 ) }
11 | for ( i in 1 : N2 ) { y2[i] ~ dbern( theta2 ) }
12 | # Prior. Independent beta distributions.
13 | theta1 ~ dbeta( 3 , 3 )
14 | theta2 ~ dbeta( 3 , 3 )
15 | }
16 | # ... end BUGS model specification
17 | " # close quote for modelstring
18 | # Write model to a file:
19 | .temp = file("model.txt","w") ; writeLines(modelstring,con=.temp) ; close(.temp)
20 | # Load model file into BRugs and check its syntax:
21 | modelCheck( "model.txt" )
22 |
23 | #------------------------------------------------------------------------------
24 | # THE DATA.
25 |
26 | # Specify the data in a form that is compatible with BRugs model, as a list:
27 | datalist = list(
28 | N1 = 7 ,
29 | # y1 = c( 1,1,1,1,1,0,0 ) ,
30 | N2 = 7 #,
31 | # y2 = c( 1,1,0,0,0,0,0 )
32 | )
33 | # Get the data into BRugs:
34 | modelData( bugsData( datalist ) ) # commented out
35 |
36 | #------------------------------------------------------------------------------
37 | # INTIALIZE THE CHAIN.
38 |
39 | modelCompile()
40 | modelGenInits()
41 |
42 | #------------------------------------------------------------------------------
43 | # RUN THE CHAINS.
44 |
45 | samplesSet( c( "theta1" , "theta2" ) ) # Keep a record of sampled "theta" values
46 | chainlength = 10000 # Arbitrary length of chain to generate.
47 | modelUpdate( chainlength ) # Actually generate the chain.
48 |
49 | #------------------------------------------------------------------------------
50 | # EXAMINE THE RESULTS.
51 |
52 | theta1Sample = samplesSample( "theta1" ) # Put sampled values in a vector.
53 | theta2Sample = samplesSample( "theta2" ) # Put sampled values in a vector.
54 |
55 | # Plot the trajectory of the last 500 sampled values.
56 | windows()
57 | par( pty="s" )
58 | plot( theta1Sample[(chainlength-500):chainlength] ,
59 | theta2Sample[(chainlength-500):chainlength] , type = "o" ,
60 | xlim = c(0,1) , xlab = bquote(theta[1]) , ylim = c(0,1) ,
61 | ylab = bquote(theta[2]) , main="BUGS Result" )
62 | # Display means in plot.
63 | theta1mean = mean(theta1Sample)
64 | theta2mean = mean(theta2Sample)
65 | if (theta1mean > .5) { xpos = 0.0 ; xadj = 0.0
66 | } else { xpos = 1.0 ; xadj = 1.0 }
67 | if (theta2mean > .5) { ypos = 0.0 ; yadj = 0.0
68 | } else { ypos = 1.0 ; yadj = 1.0 }
69 | text( xpos , ypos ,
70 | bquote(
71 | "M=" * .(signif(theta1mean,3)) * "," * .(signif(theta2mean,3))
72 | ) ,adj=c(xadj,yadj) ,cex=1.5 )
73 | dev.copy2eps(file="BernTwoBugsPriorOnly.eps")
74 |
75 | # Plot a histogram of the posterior differences of theta values.
76 | thetaDiff = theta1Sample - theta2Sample
77 | windows(7,4)
78 | source("plotPost.R")
79 | plotPost( thetaDiff , xlab=expression(theta[1]-theta[2]) ,
80 | breaks=20 , main="" )
81 | dev.copy2eps(file="BernTwoBugsPriorOnlyDiff.eps")
--------------------------------------------------------------------------------
/1e/BernTwoFurrowsBugs.R:
--------------------------------------------------------------------------------
1 | graphics.off()
2 | rm(list=ls(all=TRUE))
3 | library(BRugs) # Kruschke, J. K. (2010). Doing Bayesian data analysis:
4 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
5 | #------------------------------------------------------------------------------
6 | # THE MODEL.
7 |
8 | modelstring = "
9 | # BUGS model specification begins here...
10 | model {
11 | # Likelihood. Each flip is Bernoulli.
12 | for ( i in 1 : N1 ) { y1[i] ~ dbern( theta1 ) }
13 | for ( i in 1 : N2 ) { y2[i] ~ dbern( theta2 ) }
14 | # Prior. Curved scallops!
15 | x ~ dunif(0,1)
16 | y ~ dunif(0,1)
17 | N <- 4
18 | xt <- sin( 2*3.141593*N * x ) / (2*3.141593*N) + x
19 | yt <- 3 * y + (1/3)
20 | xtt <- pow( xt , yt )
21 | theta1 <- xtt
22 | theta2 <- y
23 | }
24 | # ... end BUGS model specification
25 | " # close quote for modelstring
26 | # Write model to a file:
27 | .temp = file("model.txt","w") ; writeLines(modelstring,con=.temp) ; close(.temp)
28 | # Load model file into BRugs and check its syntax:
29 | modelCheck( "model.txt" )
30 |
31 | #------------------------------------------------------------------------------
32 | # THE DATA.
33 |
34 | # Specify the data in a form that is compatible with BRugs model, as a list:
35 | datalist = list(
36 | N1 = 7 ,
37 | y1 = c( 1,1,1,1,1,0,0 ) ,
38 | N2 = 7 ,
39 | y2 = c( 1,1,0,0,0,0,0 )
40 | )
41 | # Get the data into BRugs:
42 | modelData( bugsData( datalist ) )
43 |
44 | #------------------------------------------------------------------------------
45 | # INTIALIZE THE CHAIN.
46 |
47 | modelCompile()
48 | modelGenInits()
49 |
50 | #------------------------------------------------------------------------------
51 | # RUN THE CHAINS.
52 |
53 | samplesSet( c( "theta1" , "theta2" ) ) # Keep a record of sampled "theta" values
54 | chainlength = 10000 # Arbitrary length of chain to generate.
55 | modelUpdate( chainlength ) # Actually generate the chain.
56 |
57 | #------------------------------------------------------------------------------
58 | # EXAMINE THE RESULTS.
59 |
60 | theta1Sample = samplesSample( "theta1" ) # Put sampled values in a vector.
61 | theta2Sample = samplesSample( "theta2" ) # Put sampled values in a vector.
62 |
63 | source("plotChains.R")
64 | plotChains("theta1")
65 | plotChains("theta2")
66 |
67 | # Plot the trajectory of the last sampled values.
68 | windows()
69 | par( pty="s" )
70 | nToPlot=2000
71 | plot( theta1Sample[(chainlength-nToPlot+1):chainlength] ,
72 | theta2Sample[(chainlength-nToPlot+1):chainlength] , type = "p" ,
73 | xlim = c(0,1) , xlab = bquote(theta[1]) , ylim = c(0,1) ,
74 | ylab = bquote(theta[2]) , main="BUGS Result" )
75 | # Display means in plot.
76 | theta1mean = mean(theta1Sample)
77 | theta2mean = mean(theta2Sample)
78 | if (theta1mean > .5) { xpos = 0.0 ; xadj = 0.0
79 | } else { xpos = 1.0 ; xadj = 1.0 }
80 | if (theta2mean > .5) { ypos = 0.0 ; yadj = 0.0
81 | } else { ypos = 1.0 ; yadj = 1.0 }
82 | text( xpos , ypos ,
83 | bquote(
84 | "M=" * .(signif(theta1mean,3)) * "," * .(signif(theta2mean,3))
85 | ) ,adj=c(xadj,yadj) ,cex=1.5 )
86 | dev.copy2eps(file="BernTwoFurrowsBugs.eps")
--------------------------------------------------------------------------------
/1e/BetaPosteriorPredictions.R:
--------------------------------------------------------------------------------
1 | # Specify known values of prior and actual data.
2 | priorA = 100
3 | priorB = 1
4 | actualDataZ = 8
5 | actualDataN = 12
6 | # Compute posterior parameter values.
7 | postA = priorA + actualDataZ
8 | postB = priorB + actualDataN - actualDataZ
9 | # Number of flips in a simulated sample should match the actual sample size:
10 | simSampleSize = actualDataN
11 | # Designate an arbitrarily large number of simulated samples.
12 | nSimSamples = 10000
13 | # Set aside a vector in which to store the simulation results.
14 | simSampleZrecord = vector( length=nSimSamples )
15 | # Now generate samples from the posterior.
16 | for ( sampleIdx in 1:nSimSamples ) {
17 | # Generate a theta value for the new sample from the posterior.
18 | sampleTheta = rbeta( 1 , postA , postB )
19 | # Generate a sample, using sampleTheta.
20 | sampleData = sample( x=c(0,1) , prob=c( 1-sampleTheta , sampleTheta ) ,
21 | size=simSampleSize , replace=TRUE )
22 | # Store the number of heads in sampleData.
23 | simSampleZrecord[ sampleIdx ] = sum( sampleData )
24 | }
25 | # Make a histogram of the number of heads in the samples.
26 | hist( simSampleZrecord )
27 | # Kruschke, J. K. (2011). Doing Bayesian data analysis: A
28 | # Tutorial with R and BUGS. Academic Press / Elsevier.
--------------------------------------------------------------------------------
/1e/BinomNHSTpoissonrate.R:
--------------------------------------------------------------------------------
1 | z_obs = 30 ; N_obs = 46
2 | nulltheta = .5
3 | tail_prob = 0 # Zero initial value for accumulation over possible N.
4 | for ( N in 1 : (3*N_obs) ) { # Start at 1 to avoid /0. 3*N_obs is arbitrary.
5 | # Create vector of z values such that z/N >= z_obs/N_obs
6 | zvec = (0:N)[ (0:N)/N >= z_obs/N_obs ]
7 | tail_prob = tail_prob + (
8 | dpois( N , N_obs ) * sum( dbinom( zvec , N , nulltheta ) ) )
9 | }
10 | show( tail_prob )
11 |
--------------------------------------------------------------------------------
/1e/BloodDataGenerator.R:
--------------------------------------------------------------------------------
1 | # Fictitious blood data. The correlations, means, and SDs used here are
2 | # fabricated for pedagogical purposes and may have no resemblance to real data.
3 | # Kruschke, J. K. (2010). Doing Bayesian data analysis:
4 | # A Tutorial with R and BUGS. Academic Press / Elsevier Science.
5 |
6 | # Specify the names of the predictors:
7 | xNames = c("Systolic","Diastolic","Weight","Cholesterol","Height","Age")
8 | nX = length(xNames) # number of predictors
9 | # SPECIFY THE CORRELATIONS BETWEEN PREDICTORS:
10 | if ( T ) { # zero correlations everywhere
11 | rMat = matrix( c( 1 , 0 , 0 , 0 , 0 , 0 ,
12 | 0 , 1 , 0 , 0 , 0 , 0 ,
13 | 0 , 0 , 1 , 0 , 0 , 0 ,
14 | 0 , 0 , 0 , 1 , 0 , 0 ,
15 | 0 , 0 , 0 , 0 , 1 , 0 ,
16 | 0 , 0 , 0 , 0 , 0 , 1 ) , ncol=nX ) }
17 | if ( F ) { # first two predictors strongly correlated
18 | rMat = matrix( c( 1 , .95, 0 , 0 , 0 , 0 ,
19 | .95, 1 , 0 , 0 , 0 , 0 ,
20 | 0 , 0 , 1 , 0 , 0 , 0 ,
21 | 0 , 0 , 0 , 1 , 0 , 0 ,
22 | 0 , 0 , 0 , 0 , 1 , 0 ,
23 | 0 , 0 , 0 , 0 , 0 , 1 ) , ncol=nX ) }
24 | if ( F ) { # first two uncorrelated, but other predictors correlated
25 | rMat = matrix( c( 1 , 0 , .6 , .2 , .1 , .1 ,
26 | 0 , 1 , .6 , .2 , .1 , .1 ,
27 | .6 , .6 , 1 , .4 , .2 , .2 ,
28 | .2 , .2 , .4 , 1 , 0 , .3 ,
29 | .1 , .1 , .2 , 0 , 1 , 0 ,
30 | .1 , .1 , .2 , .3 , 0 , 1 ) , ncol=nX ) }
31 | if ( F ) { # first two strongly correlated with others also correlated
32 | rMat = matrix( c( 1 , .95 , .6 , .2 , .1 , .1 ,
33 | .95 , 1 , .6 , .2 , .1 , .1 ,
34 | .6 , .6 , 1 , .4 , .2 , .2 ,
35 | .2 , .2 , .4 , 1 , 0 , .3 ,
36 | .1 , .1 , .2 , 0 , 1 , 0 ,
37 | .1 , .1 , .2 , .3 , 0 , 1 ) , ncol=nX ) }
38 | # SPECIFY THE NUMBER OF DATA POINTS:
39 | nSubj = 200
40 | mVec = rep(0,nX) # means of predictors
41 | require(MASS) # package needed for mvrnorm() function in next line
42 | set.seed(47405)
43 | xMat = mvrnorm( n=nSubj , mu=mVec , Sigma=rMat ) #
44 | # SPECIFY THE REGRESSION COEFFICIENTS:
45 | betaVec = c( 0 , 2 , 2 , 1 , 0 , 0.5 )
46 | # SPECIFY THE PROPORTION OF PREDICTED VALUES THAT ARE 1's, WHICH IN TURN
47 | # DETERMINES THE THRESHOLD (i.e., negative intercept). THIS IS ACCURATE ONLY
48 | # FOR LARGE REGRESSION COEFFICIENTS; OTHERWISE SPECIFY MORE EXTREME PROPORTION:
49 | proportionOnes = 0.5 # e.g., about .05 for actual .10
50 | heartAttackLinear = xMat %*% betaVec
51 | threshold = quantile( heartAttackLinear , 1-proportionOnes )
52 | heartAttackProb = 1 / ( 1 + exp( -1 * ( heartAttackLinear - threshold ) ) )
53 | y = 0*heartAttackProb
54 | for ( sIdx in 1:nSubj ) {
55 | y[sIdx] = sample( x=c(0,1) , size=1 ,
56 | prob=c( 1-heartAttackProb[sIdx] , heartAttackProb[sIdx] ) )
57 | }
58 | cat("Generated proportion of 1's in data: ",mean(y),"\n")
59 | # Convert to "real world" scale values (multiply by SD, add mean):
60 | xMat[,1] = xMat[,1] * 17 + 125 # systolic
61 | xMat[,2] = xMat[,2] * 11 + 80 # diastolic
62 | xMat[,3] = xMat[,3] * 30 + 150 # weight
63 | xMat[,4] = xMat[,4] * 30 + 130 # cholest
64 | xMat[,5] = xMat[,5] * 3 + 65 # height
65 | xMat[,6] = xMat[,6] * 15 + 50 # age
66 | xMat = round( xMat )
67 | # Assemble the values into a matrix:
68 | dataMat = cbind( y , xMat )
69 | colnames(dataMat) = c( "HeartAttack" , xNames )
70 | # Write the matrix to a table to be loaded by other programs:
71 | write.table( dataMat , file="BloodDataGeneratorOutput.txt" , row.names=F , col.names=T )
72 |
--------------------------------------------------------------------------------
/1e/DBDA_1stPrintingErrata.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/DBDA_1stPrintingErrata.pdf
--------------------------------------------------------------------------------
/1e/Feldman1988Table4data.R:
--------------------------------------------------------------------------------
1 | Feldman1988Table4data = matrix(
2 | dimnames=list( NULL , c( "group" , "subjID" , "time" , "retention" ) ) ,
3 | c( 1 , 1 , 0 , 100 ,
4 | 1 , 1 , 3 , 102 ,
5 | 1 , 1 , 4 , 87 ,
6 | 1 , 1 , 10 , 89 ,
7 | 1 , 1 , 15 , 57 ,
8 | 1 , 1 , 20 , 48 ,
9 | 1 , 1 , 25 , 43 ,
10 | 1 , 1 , 30 , 33 ,
11 | 1 , 2 , 0 , 100 ,
12 | 1 , 2 , 3 , 95 ,
13 | 1 , 2 , 4 , 91 ,
14 | 1 , 2 , 10 , 62 ,
15 | 1 , 2 , 15 , 52 ,
16 | 1 , 2 , 20 , 55 ,
17 | 1 , 2 , 25 , 45 ,
18 | 1 , 2 , 30 , 42 ,
19 | 1 , 3 , 0 , 100 ,
20 | 1 , 3 , 3 , 112 ,
21 | 1 , 3 , 4 , 72 ,
22 | 1 , 3 , 10 , 63 ,
23 | 1 , 3 , 15 , 49 ,
24 | 1 , 3 , 20 , 45 ,
25 | 1 , 3 , 25 , 29 ,
26 | 1 , 3 , 30 , 36 ,
27 | 1 , 4 , 0 , 100 ,
28 | 1 , 4 , 3 , 110 ,
29 | 1 , 4 , 4 , 129 ,
30 | 1 , 4 , 10 , 71 ,
31 | 1 , 4 , 15 , 57 ,
32 | 1 , 4 , 20 , NA ,
33 | 1 , 4 , 25 , 29 ,
34 | 1 , 4 , 30 , 32 ,
35 | 2 , 5 , 0 , 100 ,
36 | 2 , 5 , 3 , 136 ,
37 | 2 , 5 , 4 , 84 ,
38 | 2 , 5 , 10 , 84 ,
39 | 2 , 5 , 15 , 85 ,
40 | 2 , 5 , 20 , 64 ,
41 | 2 , 5 , 25 , 59 ,
42 | 2 , 5 , 30 , 57 ,
43 | 2 , 6 , 0 , 100 ,
44 | 2 , 6 , 3 , 110 ,
45 | 2 , 6 , 4 , 109 ,
46 | 2 , 6 , 10 , 83 ,
47 | 2 , 6 , 15 , 66 ,
48 | 2 , 6 , 20 , 64 ,
49 | 2 , 6 , 25 , 64 ,
50 | 2 , 6 , 30 , 53 ,
51 | 2 , 7 , 0 , 100 ,
52 | 2 , 7 , 3 , 93 ,
53 | 2 , 7 , 4 , 76 ,
54 | 2 , 7 , 10 , 77 ,
55 | 2 , 7 , 15 , 62 ,
56 | 2 , 7 , 20 , 60 ,
57 | 2 , 7 , 25 , 54 ,
58 | 2 , 7 , 30 , 53 ,
59 | 2 , 8 , 0 , 100 ,
60 | 2 , 8 , 3 , 111 ,
61 | 2 , 8 , 4 , 121 ,
62 | 2 , 8 , 10 , 85 ,
63 | 2 , 8 , 15 , 68 ,
64 | 2 , 8 , 20 , 57 ,
65 | 2 , 8 , 25 , NA ,
66 | 2 , 8 , 30 , NA
67 | ) , ncol=4 , byrow=T )
68 |
--------------------------------------------------------------------------------
/1e/FilconBrugsMuKappa.Rdata:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/FilconBrugsMuKappa.Rdata
--------------------------------------------------------------------------------
/1e/Guber1999data.txt:
--------------------------------------------------------------------------------
1 | # 1 - 16 Name of state (in quotation marks)
2 | # 18 - 22 Current expenditure per pupil in average daily attendance
3 | # in public elementary and secondary schools, 1994-95
4 | # (in thousands of dollars)
5 | # 24 - 27 Average pupil/teacher ratio in public elementary and
6 | # secondary schools, Fall 1994
7 | # 29 - 34 Estimated average annual salary of teachers in public
8 | # elementary and secondary schools, 1994-95 (in thousands of
9 | # dollars)
10 | # 36 - 37 Percentage of all eligible students taking the SAT, 1994-95
11 | # 39 - 41 Average verbal SAT score, 1994-95
12 | # 43 - 45 Average math SAT score, 1994-95
13 | # 47 - 50 Average total score on the SAT, 1994-95
14 | "Alabama" 4.405 17.2 31.144 8 491 538 1029
15 | "Alaska" 8.963 17.6 47.951 47 445 489 934
16 | "Arizona" 4.778 19.3 32.175 27 448 496 944
17 | "Arkansas" 4.459 17.1 28.934 6 482 523 1005
18 | "California" 4.992 24.0 41.078 45 417 485 902
19 | "Colorado" 5.443 18.4 34.571 29 462 518 980
20 | "Connecticut" 8.817 14.4 50.045 81 431 477 908
21 | "Delaware" 7.030 16.6 39.076 68 429 468 897
22 | "Florida" 5.718 19.1 32.588 48 420 469 889
23 | "Georgia" 5.193 16.3 32.291 65 406 448 854
24 | "Hawaii" 6.078 17.9 38.518 57 407 482 889
25 | "Idaho" 4.210 19.1 29.783 15 468 511 979
26 | "Illinois" 6.136 17.3 39.431 13 488 560 1048
27 | "Indiana" 5.826 17.5 36.785 58 415 467 882
28 | "Iowa" 5.483 15.8 31.511 5 516 583 1099
29 | "Kansas" 5.817 15.1 34.652 9 503 557 1060
30 | "Kentucky" 5.217 17.0 32.257 11 477 522 999
31 | "Louisiana" 4.761 16.8 26.461 9 486 535 1021
32 | "Maine" 6.428 13.8 31.972 68 427 469 896
33 | "Maryland" 7.245 17.0 40.661 64 430 479 909
34 | "Massachusetts" 7.287 14.8 40.795 80 430 477 907
35 | "Michigan" 6.994 20.1 41.895 11 484 549 1033
36 | "Minnesota" 6.000 17.5 35.948 9 506 579 1085
37 | "Mississippi" 4.080 17.5 26.818 4 496 540 1036
38 | "Missouri" 5.383 15.5 31.189 9 495 550 1045
39 | "Montana" 5.692 16.3 28.785 21 473 536 1009
40 | "Nebraska" 5.935 14.5 30.922 9 494 556 1050
41 | "Nevada" 5.160 18.7 34.836 30 434 483 917
42 | "New Hampshire" 5.859 15.6 34.720 70 444 491 935
43 | "New Jersey" 9.774 13.8 46.087 70 420 478 898
44 | "New Mexico" 4.586 17.2 28.493 11 485 530 1015
45 | "New York" 9.623 15.2 47.612 74 419 473 892
46 | "North Carolina" 5.077 16.2 30.793 60 411 454 865
47 | "North Dakota" 4.775 15.3 26.327 5 515 592 1107
48 | "Ohio" 6.162 16.6 36.802 23 460 515 975
49 | "Oklahoma" 4.845 15.5 28.172 9 491 536 1027
50 | "Oregon" 6.436 19.9 38.555 51 448 499 947
51 | "Pennsylvania" 7.109 17.1 44.510 70 419 461 880
52 | "Rhode Island" 7.469 14.7 40.729 70 425 463 888
53 | "South Carolina" 4.797 16.4 30.279 58 401 443 844
54 | "South Dakota" 4.775 14.4 25.994 5 505 563 1068
55 | "Tennessee" 4.388 18.6 32.477 12 497 543 1040
56 | "Texas" 5.222 15.7 31.223 47 419 474 893
57 | "Utah" 3.656 24.3 29.082 4 513 563 1076
58 | "Vermont" 6.750 13.8 35.406 68 429 472 901
59 | "Virginia" 5.327 14.6 33.987 65 428 468 896
60 | "Washington" 5.906 20.2 36.151 48 443 494 937
61 | "West Virginia" 6.107 14.8 31.944 17 448 484 932
62 | "Wisconsin" 6.930 15.9 37.746 9 501 572 1073
63 | "Wyoming" 6.160 14.9 31.285 10 476 525 1001
--------------------------------------------------------------------------------
/1e/HDIofGrid.R:
--------------------------------------------------------------------------------
1 | HDIofGrid = function( probMassVec , credMass=0.95 ) {
2 | # Arguments:
3 | # probMassVec is a vector of probability masses at each grid point.
4 | # credMass is the desired mass of the HDI region.
5 | # Return value:
6 | # A list with components:
7 | # indices is a vector of indices that are in the HDI
8 | # mass is the total mass of the included indices
9 | # height is the smallest component probability mass in the HDI
10 | # Example of use: For determining HDI of a beta(30,12) distribution
11 | # approximated on a grid:
12 | # > probDensityVec = dbeta( seq(0,1,length=201) , 30 , 12 )
13 | # > probMassVec = probDensityVec / sum( probDensityVec )
14 | # > HDIinfo = HDIofGrid( probMassVec )
15 | # > show( HDIinfo )
16 | sortedProbMass = sort( probMassVec , decreasing=T )
17 | HDIheightIdx = min( which( cumsum( sortedProbMass ) >= credMass ) )
18 | HDIheight = sortedProbMass[ HDIheightIdx ]
19 | HDImass = sum( probMassVec[ probMassVec >= HDIheight ] )
20 | return( list( indices = which( probMassVec >= HDIheight ) ,
21 | mass = HDImass , height = HDIheight ) )
22 | }
--------------------------------------------------------------------------------
/1e/HDIofICDF.R:
--------------------------------------------------------------------------------
1 | HDIofICDF = function( ICDFname , credMass=0.95 , tol=1e-8 , ... ) {
2 | # Arguments:
3 | # ICDFname is R's name for the inverse cumulative density function
4 | # of the distribution.
5 | # credMass is the desired mass of the HDI region.
6 | # tol is passed to R's optimize function.
7 | # Return value:
8 | # Highest density iterval (HDI) limits in a vector.
9 | # Example of use: For determining HDI of a beta(30,12) distribution, type
10 | # HDIofICDF( qbeta , shape1 = 30 , shape2 = 12 )
11 | # Notice that the parameters of the ICDFname must be explicitly named;
12 | # e.g., HDIofICDF( qbeta , 30 , 12 ) does not work.
13 | # Adapted and corrected from Greg Snow's TeachingDemos package.
14 | incredMass = 1.0 - credMass
15 | intervalWidth = function( lowTailPr , ICDFname , credMass , ... ) {
16 | ICDFname( credMass + lowTailPr , ... ) - ICDFname( lowTailPr , ... )
17 | }
18 | optInfo = optimize( intervalWidth , c( 0 , incredMass ) , ICDFname=ICDFname ,
19 | credMass=credMass , tol=tol , ... )
20 | HDIlowTailPr = optInfo$minimum
21 | return( c( ICDFname( HDIlowTailPr , ... ) ,
22 | ICDFname( credMass + HDIlowTailPr , ... ) ) )
23 | } # Kruschke, J. K. (2011). Doing Bayesian data analysis: A
24 | # Tutorial with R and BUGS. Elsevier Science/Academic Press.
25 |
--------------------------------------------------------------------------------
/1e/HDIofMCMC.R:
--------------------------------------------------------------------------------
1 | HDIofMCMC = function( sampleVec , credMass=0.95 ) {
2 | # Computes highest density interval from a sample of representative values,
3 | # estimated as shortest credible interval.
4 | # Arguments:
5 | # sampleVec
6 | # is a vector of representative values from a probability distribution.
7 | # credMass
8 | # is a scalar between 0 and 1, indicating the mass within the credible
9 | # interval that is to be estimated.
10 | # Value:
11 | # HDIlim is a vector containing the limits of the HDI
12 | sortedPts = sort( sampleVec )
13 | ciIdxInc = floor( credMass * length( sortedPts ) )
14 | nCIs = length( sortedPts ) - ciIdxInc
15 | ciWidth = rep( 0 , nCIs )
16 | for ( i in 1:nCIs ) {
17 | ciWidth[ i ] = sortedPts[ i + ciIdxInc ] - sortedPts[ i ]
18 | }
19 | HDImin = sortedPts[ which.min( ciWidth ) ]
20 | HDImax = sortedPts[ which.min( ciWidth ) + ciIdxInc ]
21 | HDIlim = c( HDImin , HDImax )
22 | return( HDIlim )
23 | }
24 |
--------------------------------------------------------------------------------
/1e/HtWtDataGenerator.R:
--------------------------------------------------------------------------------
1 | HtWtDataGenerator = function( nSubj , rndsd=NULL ) {
2 | # Random height, weight generator for males and females. Uses parameters from
3 | # Brainard, J. & Burmaster, D. E. (1992). Bivariate distributions for height and
4 | # weight of men and women in the United States. Risk Analysis, 12(2), 267-275.
5 | # Kruschke, J. K. (2010). Doing Bayesian data analysis:
6 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
7 |
8 | require(MASS)
9 |
10 | # Specify parameters of multivariate normal (MVN) distributions.
11 | # Men:
12 | HtMmu = 69.18
13 | HtMsd = 2.87
14 | lnWtMmu = 5.14
15 | lnWtMsd = 0.17
16 | Mrho = 0.42
17 | Mmean = c( HtMmu , lnWtMmu )
18 | Msigma = matrix( c( HtMsd^2 , Mrho * HtMsd * lnWtMsd ,
19 | Mrho * HtMsd * lnWtMsd , lnWtMsd^2 ) , nrow=2 )
20 | # Women cluster 1:
21 | HtFmu1 = 63.11
22 | HtFsd1 = 2.76
23 | lnWtFmu1 = 5.06
24 | lnWtFsd1 = 0.24
25 | Frho1 = 0.41
26 | prop1 = 0.46
27 | Fmean1 = c( HtFmu1 , lnWtFmu1 )
28 | Fsigma1 = matrix( c( HtFsd1^2 , Frho1 * HtFsd1 * lnWtFsd1 ,
29 | Frho1 * HtFsd1 * lnWtFsd1 , lnWtFsd1^2 ) , nrow=2 )
30 | # Women cluster 2:
31 | HtFmu2 = 64.36
32 | HtFsd2 = 2.49
33 | lnWtFmu2 = 4.86
34 | lnWtFsd2 = 0.14
35 | Frho2 = 0.44
36 | prop2 = 1 - prop1
37 | Fmean2 = c( HtFmu2 , lnWtFmu2 )
38 | Fsigma2 = matrix( c( HtFsd2^2 , Frho2 * HtFsd2 * lnWtFsd2 ,
39 | Frho2 * HtFsd2 * lnWtFsd2 , lnWtFsd2^2 ) , nrow=2 )
40 |
41 | # Randomly generate data values from those MVN distributions.
42 | if ( !is.null( rndsd ) ) { set.seed( rndsd ) }
43 | datamatrix = matrix( 0 , nrow=nSubj , ncol=3 )
44 | colnames(datamatrix) = c( "male" , "height" , "weight" )
45 | maleval = 1 ; femaleval = 0 # arbitrary coding values
46 | for ( i in 1:nSubj ) {
47 | # Flip coin to decide sex
48 | sex = sample( c(maleval,femaleval) , size=1 , replace=TRUE , prob=c(.5,.5) )
49 | if ( sex == maleval ) { datum = mvrnorm(n = 1, mu=Mmean, Sigma=Msigma ) }
50 | if ( sex == femaleval ) {
51 | Fclust = sample( c(1,2) , size=1 , replace=TRUE , prob=c(prop1,prop2) )
52 | if ( Fclust == 1 ) { datum = mvrnorm(n = 1, mu=Fmean1, Sigma=Fsigma1 ) }
53 | if ( Fclust == 2 ) { datum = mvrnorm(n = 1, mu=Fmean2, Sigma=Fsigma2 ) }
54 | }
55 | datamatrix[ i , ] = c( sex , round( c( datum[1] , exp( datum[2] ) ) , 1 ) )
56 | }
57 |
58 | return( datamatrix )
59 | } # end function
--------------------------------------------------------------------------------
/1e/IncomeFamszState.Rdata:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/IncomeFamszState.Rdata
--------------------------------------------------------------------------------
/1e/IntegralOfDensity.R:
--------------------------------------------------------------------------------
1 | # Graph of normal probability density function, with comb of intervals.
2 | meanval = 0.0 # Specify mean of distribution.
3 | sdval = 0.2 # Specify standard deviation of distribution.
4 | xlow = meanval - 3*sdval # Specify low end of x-axis.
5 | xhigh = meanval + 3*sdval # Specify high end of x-axis.
6 | dx = 0.02 # Specify interval width on x-axis
7 | # Specify comb points along the x axis:
8 | x = seq( from = xlow , to = xhigh , by = dx )
9 | # Compute y values, i.e., probability density at each value of x:
10 | y = ( 1/(sdval*sqrt(2*pi)) ) * exp( -.5 * ((x-meanval)/sdval)^2 )
11 | # Plot the function. "plot" draws the intervals. "lines" draws the bell curve.
12 | plot( x , y , type="h" , lwd=1 , cex.axis=1.5
13 | , xlab="x" , ylab="p(x)" , cex.lab=1.5
14 | , main="Normal Probability Density" , cex.main=1.5 )
15 | lines( x , y )
16 | # Approximate the integral as the sum of width * height for each interval.
17 | area = sum( dx * y )
18 | # Display info in the graph.
19 | text( -sdval , .9*max(y) , bquote( paste(mu ," = " ,.(meanval)) )
20 | , adj=c(1,.5) )
21 | text( -sdval , .8*max(y) , bquote( paste(sigma ," = " ,.(sdval)) )
22 | , adj=c(1,.5) )
23 | text( sdval , .9*max(y) , bquote( paste(Delta , "x = " ,.(dx)) )
24 | , adj=c(0,.5) )
25 | text( sdval , .8*max(y) ,
26 | bquote(
27 | paste( sum(,x,) , " " , Delta , "x p(x) = " , .(signif(area,3)) )
28 | ) , adj=c(0,.5) )
29 | # To save graphs, please see update at
30 | # http://doingbayesiandataanalysis.blogspot.com/2013/01/uniform-r-code-for-opening-saving.html
31 |
--------------------------------------------------------------------------------
/1e/Kruschke1996CSdatsum.Rdata:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/Kruschke1996CSdatsum.Rdata
--------------------------------------------------------------------------------
/1e/MaxwellDelaneyCh12data.csv:
--------------------------------------------------------------------------------
1 | Y,Subj,Angle,Age,Angle.Int,Age.Int
2 | 450,1,B1(Zero),A1(Young),1,1
3 | 510,1,B2(Four),A1(Young),2,1
4 | 630,1,B3(Eight),A1(Young),3,1
5 | 390,2,B1(Zero),A1(Young),1,1
6 | 480,2,B2(Four),A1(Young),2,1
7 | 540,2,B3(Eight),A1(Young),3,1
8 | 570,3,B1(Zero),A1(Young),1,1
9 | 630,3,B2(Four),A1(Young),2,1
10 | 660,3,B3(Eight),A1(Young),3,1
11 | 450,4,B1(Zero),A1(Young),1,1
12 | 660,4,B2(Four),A1(Young),2,1
13 | 720,4,B3(Eight),A1(Young),3,1
14 | 510,5,B1(Zero),A1(Young),1,1
15 | 660,5,B2(Four),A1(Young),2,1
16 | 630,5,B3(Eight),A1(Young),3,1
17 | 360,6,B1(Zero),A1(Young),1,1
18 | 450,6,B2(Four),A1(Young),2,1
19 | 450,6,B3(Eight),A1(Young),3,1
20 | 510,7,B1(Zero),A1(Young),1,1
21 | 600,7,B2(Four),A1(Young),2,1
22 | 720,7,B3(Eight),A1(Young),3,1
23 | 510,8,B1(Zero),A1(Young),1,1
24 | 660,8,B2(Four),A1(Young),2,1
25 | 780,8,B3(Eight),A1(Young),3,1
26 | 510,9,B1(Zero),A1(Young),1,1
27 | 660,9,B2(Four),A1(Young),2,1
28 | 660,9,B3(Eight),A1(Young),3,1
29 | 510,10,B1(Zero),A1(Young),1,1
30 | 540,10,B2(Four),A1(Young),2,1
31 | 660,10,B3(Eight),A1(Young),3,1
32 | 420,11,B1(Zero),A2(Old),1,2
33 | 570,11,B2(Four),A2(Old),2,2
34 | 690,11,B3(Eight),A2(Old),3,2
35 | 600,12,B1(Zero),A2(Old),1,2
36 | 720,12,B2(Four),A2(Old),2,2
37 | 810,12,B3(Eight),A2(Old),3,2
38 | 450,13,B1(Zero),A2(Old),1,2
39 | 540,13,B2(Four),A2(Old),2,2
40 | 690,13,B3(Eight),A2(Old),3,2
41 | 630,14,B1(Zero),A2(Old),1,2
42 | 660,14,B2(Four),A2(Old),2,2
43 | 780,14,B3(Eight),A2(Old),3,2
44 | 420,15,B1(Zero),A2(Old),1,2
45 | 570,15,B2(Four),A2(Old),2,2
46 | 780,15,B3(Eight),A2(Old),3,2
47 | 600,16,B1(Zero),A2(Old),1,2
48 | 780,16,B2(Four),A2(Old),2,2
49 | 870,16,B3(Eight),A2(Old),3,2
50 | 630,17,B1(Zero),A2(Old),1,2
51 | 690,17,B2(Four),A2(Old),2,2
52 | 870,17,B3(Eight),A2(Old),3,2
53 | 480,18,B1(Zero),A2(Old),1,2
54 | 570,18,B2(Four),A2(Old),2,2
55 | 720,18,B3(Eight),A2(Old),3,2
56 | 690,19,B1(Zero),A2(Old),1,2
57 | 750,19,B2(Four),A2(Old),2,2
58 | 900,19,B3(Eight),A2(Old),3,2
59 | 510,20,B1(Zero),A2(Old),1,2
60 | 690,20,B2(Four),A2(Old),2,2
61 | 810,20,B3(Eight),A2(Old),3,2
62 |
--------------------------------------------------------------------------------
/1e/McDonaldSK1991data.txt:
--------------------------------------------------------------------------------
1 | # From http://udel.edu/~mcdonald/statanovasig.html
2 | # "Here are some data on a shell measurement (the length of the anterior
3 | # adductor muscle scar, standardized by dividing by length) in the mussel
4 | # Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
5 | # Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland,
6 | # taken from a much larger data set used in McDonald et al. (1991)."
7 | #
8 | # McDonald, J. H., R. Seed and R. K. Koehn. 1991.
9 | # Allozymes and morphometric characters of three species of Mytilus
10 | # in the Northern and Southern Hemispheres.
11 | # Mar. Biol. 111:323-333.
12 | #
13 | # Group code:
14 | # 1=Tillamook,Oregon
15 | # 2=Newport,Oregon
16 | # 3=Petersburg,Alaska
17 | # 4=Magadan,Russia
18 | # 5=Tvarminne,Finland
19 | Group Size Site
20 | 1 0.0571 OregonT
21 | 1 0.0813 OregonT
22 | 1 0.0831 OregonT
23 | 1 0.0976 OregonT
24 | 1 0.0817 OregonT
25 | 1 0.0859 OregonT
26 | 1 0.0735 OregonT
27 | 1 0.0659 OregonT
28 | 1 0.0923 OregonT
29 | 1 0.0836 OregonT
30 | 2 0.0873 OregonN
31 | 2 0.0662 OregonN
32 | 2 0.0672 OregonN
33 | 2 0.0819 OregonN
34 | 2 0.0749 OregonN
35 | 2 0.0649 OregonN
36 | 2 0.0835 OregonN
37 | 2 0.0725 OregonN
38 | 3 0.0974 Alaska
39 | 3 0.1352 Alaska
40 | 3 0.0817 Alaska
41 | 3 0.1016 Alaska
42 | 3 0.0968 Alaska
43 | 3 0.1064 Alaska
44 | 3 0.1050 Alaska
45 | 4 0.1033 Russia
46 | 4 0.0915 Russia
47 | 4 0.0781 Russia
48 | 4 0.0685 Russia
49 | 4 0.0677 Russia
50 | 4 0.0697 Russia
51 | 4 0.0764 Russia
52 | 4 0.0689 Russia
53 | 5 0.0703 Finland
54 | 5 0.1026 Finland
55 | 5 0.0956 Finland
56 | 5 0.0973 Finland
57 | 5 0.1039 Finland
58 | 5 0.1045 Finland
59 | #
60 | # http://udel.edu/~mcdonald/statanovaunplanned.html
61 | # shows that Tukey-Kramer method of unplanned comparisons
62 | # groups
63 | # Newport/Magadan/Tillamook (2/4/1),
64 | # Magadan/Tillamook/Tvarminne (4/1/5),
65 | # and Tvarminne/Petersburg (5/3).
66 | #
67 | # From http://udel.edu/~mcdonald/statanovaplanned.html:
68 | # Really important note about planned comparisons
69 | # Planned comparisons must be planned before you look at the data. If you
70 | # look at some data, pick out an interesting comparison, then analyze it as
71 | # if it were a planned comparison, you will be committing scientific fraud.
72 | # For example, if you look at the mean arch heights for the nine sports, see
73 | # that cross-country has the lowest mean and swimming has the highest mean,
74 | # then compare just those two means, your P-value will be much too low. This
75 | # is because there are 36 possible pairwise comparisons in a set of 9 means.
76 | # You expect 5 percent, or 1 out of 20, tests to be "significant" at the
77 | # P<0.05 level, even if all the data really fit the null hypothesis, so
78 | # there's a good chance that the most extreme comparison in a set of 36
79 | # will have a P-value less than 0.05.
80 | # It would be acceptable to run a pilot experiment and plan your planned
81 | # comparisons based on the results of the pilot experiment. However, if you
82 | # do this you could not include the data from the pilot experiment in the
83 | # analysis; you would have to limit your anova to the new data.
--------------------------------------------------------------------------------
/1e/McIntyre1994data.csv:
--------------------------------------------------------------------------------
1 | Brand,Tar,Nic,Wt,CO
2 | Alpine,14.1,0.86,0.9853,13.6
3 | BensonAndHedges,16.0,1.06,1.0938,16.6
4 | BullDurham,29.8,2.03,1.1650,23.5
5 | CamelLights,8.0,0.67,0.9280,10.2
6 | Carlton,4.1,0.40,0.9462,5.4
7 | Chesterfield,15.0,1.04,0.8885,15.0
8 | GoldenLights,8.8,0.76,1.0267,9.0
9 | Kent,12.4,0.95,0.9225,12.3
10 | Kool,16.6,1.12,0.9372,16.3
11 | LandM,14.9,1.02,0.8858,15.4
12 | LarkLights,13.7,1.01,0.9643,13.0
13 | Marlboro,15.1,0.90,0.9316,14.4
14 | Merit,7.8,0.57,0.9705,10.0
15 | MultiFilter,11.4,0.78,1.1240,10.2
16 | NewportLights,9.0,0.74,0.8517,9.5
17 | Now,1.0,0.13,0.7851,1.5
18 | OldGold,17.0,1.26,0.9186,18.5
19 | PallMallLight,12.8,1.08,1.0395,12.6
20 | Raleigh,15.8,0.96,0.9573,17.5
21 | SalemUltra,4.5,0.42,0.9106,4.9
22 | Tareyton,14.5,1.01,1.0070,15.9
23 | True,7.3,0.61,0.9806,8.5
24 | ViceroyRichLight,8.6,0.69,0.9693,10.6
25 | VirginiaSlims,15.2,1.02,0.9496,13.9
26 | WinstonLights,12.0,0.82,1.1184,14.9
27 |
--------------------------------------------------------------------------------
/1e/NHSTtwoTierStoppingExercise.R:
--------------------------------------------------------------------------------
1 | # For NHST exercise regarding two-tier testing.
2 |
3 | N1 = 30 # Number of flips for first test. Try 17.
4 | N2 = 15 # Number of _additional_ flips for second test. Try 27 or 50.
5 |
6 | theta = .5 # Hypothesized bias of coin.
7 | FAmax = .05 # False Alarm maximum for a single test.
8 | NT = N1 + N2 # Total number of flips.
9 |
10 | # Determine critical values for N1:
11 | # EXPLAIN what each function does and why, including
12 | # dbinom, cumsum, which, max, and (0:N)[...]
13 | loCritN1 = (0:N1)[ max( which( cumsum( dbinom(0:N1,N1,theta) ) <= FAmax/2 ) ) ]
14 | hiCritN1 = (N1:0)[ max( which( cumsum( dbinom(N1:0,N1,theta) ) <= FAmax/2 ) ) ]
15 | # Compute actual false alarm rate for those critical values.
16 | # EXPLAIN what this does and why.
17 | FA1 = sum( ( 0:N1 <= loCritN1 | 0:N1 >= hiCritN1 ) * dbinom(0:N1,N1,theta) )
18 | cat( "N1:",N1 , ", lo:",loCritN1 , ", hi:",hiCritN1 , ", FA:",FA1 , "\n" )
19 |
20 | # Determine critical values for NT:
21 | # EXPLAIN what each function does and why, including
22 | # dbinom, cumsum, which, max, and (0:N)[...]
23 | loCritNT = (0:NT)[ max( which( cumsum( dbinom(0:NT,NT,theta) ) <= FAmax/2 ) ) ]
24 | hiCritNT = (NT:0)[ max( which( cumsum( dbinom(NT:0,NT,theta) ) <= FAmax/2 ) ) ]
25 | # Compute actual false alarm rate for those critical values.
26 | # EXPLAIN what this does and why.
27 | FAT = sum( ( 0:NT <= loCritNT | 0:NT >= hiCritNT ) * dbinom(0:NT,NT,theta) )
28 | cat( "NT:",NT , ", lo:",loCritNT , ", hi:",hiCritNT , ", FA:",FAT , "\n" )
29 |
30 | # Determine actual false alarm rate for the two-tier test:
31 | # EXPLAIN each of the matrices below --- what is in each one?
32 | Z1mat = matrix( 0:N1 , nrow=N2+1 , ncol=N1+1 , byrow=TRUE )
33 | ZTmat = outer( 0:N2 , 0:N1 , "+" )
34 | pZTmat = outer( dbinom( 0:N2 , N2 , theta ) , dbinom( 0:N1 , N1 , theta ) )
35 | # EXPLAIN the matrices in computation below.
36 | FA1or2 = sum( ( ( ZTmat <= loCritNT | ZTmat >= hiCritNT ) # double dagger matrix
37 | | ( Z1mat <= loCritN1 | Z1mat >= hiCritN1 ) # single dagger matrix
38 | ) * pZTmat )
39 | cat( "Two tier FA:" , FA1or2 , "\n" )
40 |
--------------------------------------------------------------------------------
/1e/NonhomogVarData.csv:
--------------------------------------------------------------------------------
1 | "Group","Y"
2 | "A",97.0346046301669
3 | "A",99.5840324686587
4 | "A",90.6335771720302
5 | "A",96.056674808999
6 | "A",101.38757384718
7 | "A",76.7423933294126
8 | "A",106.927967035102
9 | "A",99.2562863527593
10 | "A",94.9026877394272
11 | "A",97.4742026162647
12 | "B",98.4156093240945
13 | "B",98.5508210715387
14 | "B",97.8816388855678
15 | "B",98.3610497694865
16 | "B",100.583595793456
17 | "B",99.738352775682
18 | "B",100.076151871869
19 | "B",99.3270352940162
20 | "B",97.5220992761716
21 | "B",99.5436459381169
22 | "C",101.51855213587
23 | "C",101.119429398216
24 | "C",100.788053507865
25 | "C",101.446695617282
26 | "C",101.273346853805
27 | "C",101.979996585281
28 | "C",101.960788059964
29 | "C",103.788867473592
30 | "C",102.721861995703
31 | "C",103.40240837242
32 | "D",116.445403636616
33 | "D",93.4953715907068
34 | "D",92.1264605521122
35 | "D",101.510964668199
36 | "D",103.749160692557
37 | "D",108.972337053729
38 | "D",107.324123408796
39 | "D",115.359229119151
40 | "D",104.064773808712
41 | "D",106.95217546942
42 |
--------------------------------------------------------------------------------
/1e/OrdinalProbitDataGenerator.R:
--------------------------------------------------------------------------------
1 | OrdinalProbitDataGenerator = function( nData , nYlevels=5 ,
2 | normPrec=1 , slope=c(.5,.5) ,
3 | thresh=c(-Inf,seq(-1.25,1.25,length=nYlevels-1),Inf) ,
4 | makePlots = FALSE , rndSeed=NULL ) {
5 |
6 | if ( !is.null(rndSeed) ) { set.seed( rndSeed ) }
7 |
8 | # Generate random _standardized_ X values.
9 | nPredictors = length(slope)
10 | Xdata = matrix( rnorm( nPredictors*nData , 0 , 1 ) ,
11 | nrow=nData, ncol=nPredictors)
12 |
13 | # Standardize the X values:
14 | for ( colIdx in 1:NCOL(Xdata) ) {
15 | mX = mean( Xdata[,colIdx] )
16 | sdX = sd( Xdata[,colIdx] )
17 | Xdata[,colIdx] = ( Xdata[,colIdx] - mX ) / sdX
18 | }
19 |
20 | # Generate continuous mu values as linear function of X.
21 | bias = 0
22 | slope = slope / sum(abs(slope))
23 | dim(slope) = c(nPredictors,1) # make it a column vector
24 | mu = bias + Xdata %*% slope
25 |
26 | # Convert continuous mu values to discrete (ordinal) Y values:
27 | # Utility function: Cumulative normal, parameterized with precision not SD.
28 | cumnorm = function( x , prec=1 ) {
29 | y = pnorm( x , mean=0 , sd=(1/sqrt(prec)) )
30 | return( y )
31 | }
32 | # Randomly generate discrete Y values based on proximity to bin thresholds.
33 | Ydata = matrix( 0 , nrow=nData , ncol=1 )
34 | for ( subjIdx in 1:nData ) {
35 | Yprob = ( cumnorm( thresh[2:(nYlevels+1)] - mu[subjIdx] , normPrec )
36 | - cumnorm( thresh[1:(nYlevels)] - mu[subjIdx] , normPrec ) )
37 | Ydata[subjIdx] = sample( 1:nYlevels , prob = Yprob ,
38 | size=1 , replace=T )
39 | }
40 |
41 | # Combine X and Y into a data matrix.
42 | datamatrix = cbind( Ydata , Xdata )
43 | colnames( datamatrix ) = c( "Y" , paste("X",1:nPredictors,sep="") )
44 |
45 | # Plot the data.
46 | if ( makePlots ) {
47 | colorlist = rep( c("black","red","blue","green","gold","purple","cyan","brown"),
48 | length=nYlevels )
49 | # 2D scatterplot
50 | xrange = range(datamatrix[,2])
51 | yrange = range(datamatrix[,3])
52 | rowIdx = ( datamatrix[,1] == 1 )
53 | plot( datamatrix[rowIdx,2] , datamatrix[rowIdx,3] , pch=as.character(1) ,
54 | col=colorlist[respIdx=1] ,
55 | main=paste("Ordinal Values (1-",nYlevels,")",sep="") ,
56 | #xlim=c(10000,90000) , ylim=c(0,10) ,
57 | xlim=xrange , ylim=yrange ,
58 | xlab="X1" , ylab="X2" )
59 | for ( respIdx in 2:nYlevels ) {
60 | rowIdx = ( datamatrix[,1] == respIdx )
61 | points( datamatrix[rowIdx,2] , datamatrix[rowIdx,3] , col=colorlist[respIdx] ,
62 | pch=as.character(respIdx) )
63 | }
64 |
65 | } # end if makePlots
66 |
67 | return( datamatrix )
68 |
69 | } # end function # Kruschke, J. K. (2011). Doing Bayesian data analysis: A
70 | # Tutorial with R and BUGS. Academic Press / Elsevier.
--------------------------------------------------------------------------------
/1e/QianS2007SeaweedData.txt:
--------------------------------------------------------------------------------
1 | COVER,BLOCK,TREAT
2 | 14.00,BLOCK 1,CONTROL
3 | 23.00,BLOCK 1,CONTROL
4 | 22.00,BLOCK 2,CONTROL
5 | 35.00,BLOCK 2,CONTROL
6 | 67.00,BLOCK 3,CONTROL
7 | 82.00,BLOCK 3,CONTROL
8 | 94.00,BLOCK 4,CONTROL
9 | 95.00,BLOCK 4,CONTROL
10 | 34.00,BLOCK 5,CONTROL
11 | 53.00,BLOCK 5,CONTROL
12 | 58.00,BLOCK 6,CONTROL
13 | 75.00,BLOCK 6,CONTROL
14 | 19.00,BLOCK 7,CONTROL
15 | 47.00,BLOCK 7,CONTROL
16 | 53.00,BLOCK 8,CONTROL
17 | 61.00,BLOCK 8,CONTROL
18 | 4.00,BLOCK 1,L
19 | 4.00,BLOCK 1,L
20 | 7.00,BLOCK 2,L
21 | 8.00,BLOCK 2,L
22 | 28.00,BLOCK 3,L
23 | 58.00,BLOCK 3,L
24 | 27.00,BLOCK 4,L
25 | 35.00,BLOCK 4,L
26 | 11.00,BLOCK 5,L
27 | 33.00,BLOCK 5,L
28 | 16.00,BLOCK 6,L
29 | 31.00,BLOCK 6,L
30 | 6.00,BLOCK 7,L
31 | 8.00,BLOCK 7,L
32 | 15.00,BLOCK 8,L
33 | 17.00,BLOCK 8,L
34 | 11.00,BLOCK 1,f
35 | 24.00,BLOCK 1,f
36 | 14.00,BLOCK 2,f
37 | 31.00,BLOCK 2,f
38 | 52.00,BLOCK 3,f
39 | 59.00,BLOCK 3,f
40 | 83.00,BLOCK 4,f
41 | 89.00,BLOCK 4,f
42 | 33.00,BLOCK 5,f
43 | 34.00,BLOCK 5,f
44 | 39.00,BLOCK 6,f
45 | 52.00,BLOCK 6,f
46 | 43.00,BLOCK 7,f
47 | 53.00,BLOCK 7,f
48 | 30.00,BLOCK 8,f
49 | 37.00,BLOCK 8,f
50 | 3.00,BLOCK 1,Lf
51 | 5.00,BLOCK 1,Lf
52 | 3.00,BLOCK 2,Lf
53 | 6.00,BLOCK 2,Lf
54 | 9.00,BLOCK 3,Lf
55 | 31.00,BLOCK 3,Lf
56 | 21.00,BLOCK 4,Lf
57 | 57.00,BLOCK 4,Lf
58 | 5.00,BLOCK 5,Lf
59 | 9.00,BLOCK 5,Lf
60 | 26.00,BLOCK 6,Lf
61 | 43.00,BLOCK 6,Lf
62 | 4.00,BLOCK 7,Lf
63 | 12.00,BLOCK 7,Lf
64 | 12.00,BLOCK 8,Lf
65 | 18.00,BLOCK 8,Lf
66 | 10.00,BLOCK 1,fF
67 | 13.00,BLOCK 1,fF
68 | 10.00,BLOCK 2,fF
69 | 15.00,BLOCK 2,fF
70 | 44.00,BLOCK 3,fF
71 | 50.00,BLOCK 3,fF
72 | 57.00,BLOCK 4,fF
73 | 73.00,BLOCK 4,fF
74 | 26.00,BLOCK 5,fF
75 | 42.00,BLOCK 5,fF
76 | 38.00,BLOCK 6,fF
77 | 42.00,BLOCK 6,fF
78 | 29.00,BLOCK 7,fF
79 | 36.00,BLOCK 7,fF
80 | 11.00,BLOCK 8,fF
81 | 40.00,BLOCK 8,fF
82 | 1.00,BLOCK 1,LfF
83 | 2.00,BLOCK 1,LfF
84 | 3.00,BLOCK 2,LfF
85 | 5.00,BLOCK 2,LfF
86 | 6.00,BLOCK 3,LfF
87 | 9.00,BLOCK 3,LfF
88 | 7.00,BLOCK 4,LfF
89 | 22.00,BLOCK 4,LfF
90 | 5.00,BLOCK 5,LfF
91 | 6.00,BLOCK 5,LfF
92 | 10.00,BLOCK 6,LfF
93 | 17.00,BLOCK 6,LfF
94 | 5.00,BLOCK 7,LfF
95 | 14.00,BLOCK 7,LfF
96 | 5.00,BLOCK 8,LfF
97 | 7.00,BLOCK 8,LfF
--------------------------------------------------------------------------------
/1e/RatLives.Rdata:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/RatLives.Rdata
--------------------------------------------------------------------------------
/1e/RunningProportion.R:
--------------------------------------------------------------------------------
1 | # Goal: Toss a coin N times and compute the running proportion of heads.
2 | N = 500 # Specify the total number of flips, denoted N.
3 | # Generate a random sample of N flips for a fair coin (heads=1, tails=0);
4 | # the function "sample" is part of R:
5 | #set.seed(47405) # Uncomment to set the "seed" for the random number generator.
6 | flipsequence = sample( x=c(0,1) , prob=c(.5,.5) , size=N , replace=TRUE )
7 | # Compute the running proportion of heads:
8 | r = cumsum( flipsequence ) # The function "cumsum" is built in to R.
9 | n = 1:N # n is a vector.
10 | runprop = r / n # component by component division.
11 | # Graph the running proportion:
12 | # To learn about the parameters of the plot function,
13 | # type help('par') at the R command prompt.
14 | # Note that "c" is a function in R.
15 | plot( n , runprop , type="o" , log="x" ,
16 | xlim=c(1,N) , ylim=c(0.0,1.0) , cex.axis=1.5 ,
17 | xlab="Flip Number" , ylab="Proportion Heads" , cex.lab=1.5 ,
18 | main="Running Proportion of Heads" , cex.main=1.5 )
19 | # Plot a dotted horizontal line at y=.5, just as a reference line:
20 | lines( c(1,N) , c(.5,.5) , lty=3 )
21 | # Display the beginning of the flip sequence. These string and character
22 | # manipulations may seem mysterious, but you can de-mystify by unpacking
23 | # the commands starting with the innermost parentheses or brackets and
24 | # moving to the outermost.
25 | flipletters = paste( c("T","H")[ flipsequence[ 1:10 ] + 1 ] , collapse="" )
26 | displaystring = paste( "Flip Sequence = " , flipletters , "..." , sep="" )
27 | text( 5 , .9 , displaystring , adj=c(0,1) , cex=1.3 )
28 | # Display the relative frequency at the end of the sequence.
29 | text( N , .3 , paste("End Proportion =",runprop[N]) , adj=c(1,0) , cex=1.3 )
30 | # To save graphs, please see update at
31 | # http://doingbayesiandataanalysis.blogspot.com/2013/01/uniform-r-code-for-opening-saving.html
--------------------------------------------------------------------------------
/1e/Salary.csv:
--------------------------------------------------------------------------------
1 | "Org","Post","Salary"
2 | "CEDP","FT1",89504
3 | "CEDP","FT1",106554
4 | "CHEM","FT1",108158
5 | "CEDP","FT1",92961
6 | "CHEM","FT1",154703
7 | "CEDP","FT1",81840
8 | "BFIN","FT1",238000
9 | "THTR","FT1",86794
10 | "CEDP","FT1",84121
11 | "THTR","FT1",80450
12 | "CEDP","FT1",98434
13 | "CHEM","FT1",194192
14 | "CEDP","FT1",92896
15 | "THTR","FT1",72240
16 | "CEDP","FT1",88374
17 | "BFIN","FT1",234000
18 | "THTR","FT1",81566
19 | "CEDP","FT1",102300
20 | "CHEM","FT1",159753
21 | "CHEM","FT1",121313
22 | "CHEM","FT2",123200
23 | "BFIN","FT2",183000
24 | "THTR","FT2",62611
25 | "BFIN","FT2",222000
26 | "CEDP","FT2",63000
27 | "CHEM","FT2",120000
28 | "BFIN","FT2",200000
29 | "CEDP","FT2",65115
30 | "BFIN","FT2",198000
31 | "CEDP","FT2",83762
32 | "CEDP","FT2",75559
33 | "BFIN","FT2",146000
34 | "CHEM","FT2",83164
35 | "CHEM","FT2",135794
36 | "CHEM","FT2",82762
37 | "BFIN","FT2",134000
38 | "CHEM","FT2",88147
39 | "THTR","FT2",59210
40 | "CEDP","FT2",66186
41 | "THTR","FT2",63924
42 | "CHEM","FT2",123610
43 | "CHEM","FT2",88271
44 | "THTR","FT2",62315
45 | "BFIN","FT2",174000
46 | "THTR","FT2",63261
47 | "CEDP","FT2",66794
48 | "THTR","FT2",71706
49 | "CEDP","FT2",79236
50 | "CHEM","FT2",104568
51 | "BFIN","FT2",180000
52 | "CHEM","FT3",77169
53 | "CHEM","FT3",81773
54 | "CEDP","FT3",59568
55 | "CHEM","FT3",75000
56 | "THTR","FT3",53000
57 | "CHEM","FT3",75000
58 | "THTR","FT3",51991
59 | "CEDP","FT3",57000
60 | "CHEM","FT3",75000
61 | "THTR","FT3",56985
62 | "THTR","FT3",51365
63 | "CHEM","FT3",76714
64 | "CEDP","FT3",58890
65 | "BFIN","FT3",188000
66 | "THTR","FT3",52140
67 | "THTR","FT3",53000
68 | "CHEM","FT3",80017
69 | "BFIN","FT3",165000
70 | "THTR","FT3",53000
71 | "CEDP","FT3",57443
72 | "BFIN","FT3",190000
73 | "CHEM","FT3",75000
74 | "BFIN","FT3",177000
75 | "CEDP","FT3",57443
76 | "BFIN","FT3",180000
77 | "CHEM","FT3",78000
78 | "BFIN","FT3",180000
79 | "CHEM","FT3",68523
80 | "BFIN","FT3",176000
81 | "CEDP","FT3",57000
82 | "CEDP","FT3",58500
83 | "CEDP","FT3",57443
84 | "BFIN","FT3",171000
85 | "BFIN","FT3",176000
86 |
--------------------------------------------------------------------------------
/1e/SimpleGraph.R:
--------------------------------------------------------------------------------
1 | x = seq( from = -2 , to = 2 , by = 0.1 ) # Specify vector of x values.
2 | y = x^2 # Specify corresponding y values.
3 | plot( x , y , type = "l" ) # Make a graph of the x,y points.
4 | # To save graphs, please see update at
5 | # http://doingbayesiandataanalysis.blogspot.com/2013/01/uniform-r-code-for-opening-saving.html
--------------------------------------------------------------------------------
/1e/SolariLS2008data.txt:
--------------------------------------------------------------------------------
1 | # Data from Solari, Liseo & Sun 2008
2 | #
3 | # (Pompilj and Napolitani, 1954). An experiment is conducted
4 | # to analyze the possible influence of some types of manuring
5 | # on the ascorbic acid content in tomatoes. The treatments
6 | # under study are nine manures obtained as different
7 | # combinations of calcium nitrate and calcium superphosphate.
8 | #
9 | # T1 T2 T3 T4 T5 T6 T7 T8 T9
10 | # 7.12 4.42 6.49 8.07 8.05 5.09 5.87 6.57 4.13
11 | # 7.16 5.68 8.09 2.86 5.82 4.57 5.36 5.08 7.31
12 | # 4.57 5.15 8.79 6.84 2.47 6.06 5.85 5.95 4.47
13 | # 3.79 3.83 8.44 6.85 3.28 4.87 6.27 7.51 2.53
14 | # 4.20 3.30 6.11 4.12 5.38 4.52 5.96 3.79 3.96
15 | # 5.84 4.44 5.17 3.32 3.98 5.08 4.95 4.33 5.30
16 | # 5.56 3.51 8.13 1.74 6.08 4.29 5.85 3.70 2.66
17 | # 5.02 4.60 7.58 1.74 6.28 6.19 4.70 5.21 4.12
18 | # 3.69 4.85 6.47 1.57 5.72 3.45 1.53 4.48 3.54
19 | # 2.99 4.84 5.45 3.02 2.88 5.85 3.88 5.17 2.98
20 | # 4.99 5.45 6.18 5.08 6.40 2.51 2.88 4.69 5.08
21 | # 2.16 4.71 4.34 4.96 4.58 4.93 2.07 2.12 5.15
22 | Type Acid
23 | 1 7.12
24 | 1 7.16
25 | 1 4.57
26 | 1 3.79
27 | 1 4.20
28 | 1 5.84
29 | 1 5.56
30 | 1 5.02
31 | 1 3.69
32 | 1 2.99
33 | 1 4.99
34 | 1 2.16
35 | 2 4.42
36 | 2 5.68
37 | 2 5.15
38 | 2 3.83
39 | 2 3.30
40 | 2 4.44
41 | 2 3.51
42 | 2 4.60
43 | 2 4.85
44 | 2 4.84
45 | 2 5.45
46 | 2 4.71
47 | 3 6.49
48 | 3 8.09
49 | 3 8.79
50 | 3 8.44
51 | 3 6.11
52 | 3 5.17
53 | 3 8.13
54 | 3 7.58
55 | 3 6.47
56 | 3 5.45
57 | 3 6.18
58 | 3 4.34
59 | 4 8.07
60 | 4 2.86
61 | 4 6.84
62 | 4 6.85
63 | 4 4.12
64 | 4 3.32
65 | 4 1.74
66 | 4 1.74
67 | 4 1.57
68 | 4 3.02
69 | 4 5.08
70 | 4 4.96
71 | 5 8.05
72 | 5 5.82
73 | 5 2.47
74 | 5 3.28
75 | 5 5.38
76 | 5 3.98
77 | 5 6.08
78 | 5 6.28
79 | 5 5.72
80 | 5 2.88
81 | 5 6.40
82 | 5 4.58
83 | 6 5.09
84 | 6 4.57
85 | 6 6.06
86 | 6 4.87
87 | 6 4.52
88 | 6 5.08
89 | 6 4.29
90 | 6 6.19
91 | 6 3.45
92 | 6 5.85
93 | 6 2.51
94 | 6 4.93
95 | 7 5.87
96 | 7 5.36
97 | 7 5.85
98 | 7 6.27
99 | 7 5.96
100 | 7 4.95
101 | 7 5.85
102 | 7 4.70
103 | 7 1.53
104 | 7 3.88
105 | 7 2.88
106 | 7 2.07
107 | 8 6.57
108 | 8 5.08
109 | 8 5.95
110 | 8 7.51
111 | 8 3.79
112 | 8 4.33
113 | 8 3.70
114 | 8 5.21
115 | 8 4.48
116 | 8 5.17
117 | 8 4.69
118 | 8 2.12
119 | 9 4.13
120 | 9 7.31
121 | 9 4.47
122 | 9 2.53
123 | 9 3.96
124 | 9 5.30
125 | 9 2.66
126 | 9 4.12
127 | 9 3.54
128 | 9 2.98
129 | 9 5.08
130 | 9 5.15
--------------------------------------------------------------------------------
/1e/SolutionsManual_Kruschke_DoingBayesianDataAnalysis.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/SolutionsManual_Kruschke_DoingBayesianDataAnalysis.pdf
--------------------------------------------------------------------------------
/1e/Systems.Rdata:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/1e/Systems.Rdata
--------------------------------------------------------------------------------
/1e/ToyModelComp.R:
--------------------------------------------------------------------------------
1 | graphics.off()
2 | rm(list=ls(all=TRUE))
3 | library(BRugs) # Kruschke, J. K. (2010). Doing Bayesian data analysis:
4 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
5 | #------------------------------------------------------------------------------
6 | # THE MODEL.
7 |
8 | modelstring = "
9 | # BUGS model specification begins here...
10 | model {
11 | for ( i in 1:nFlip ) {
12 | # Likelihood:
13 | y[i] ~ dbern( theta )
14 | }
15 | # Prior
16 | theta <- ( (2-mdlIdx) * 1/(1+exp( -nu )) # theta from model index 1
17 | + (mdlIdx-1) * exp( -eta ) ) # theta from model index 2
18 | nu ~ dnorm(0,.1) # 0,.1 vs 1,1
19 | eta ~ dgamma(.1,.1) # .1,.1 vs 1,1
20 | # Hyperprior on model index:
21 | mdlIdx ~ dcat( modelProb[] )
22 | modelProb[1] <- .5
23 | modelProb[2] <- .5
24 | }
25 | # ... end BUGS model specification
26 | " # close quote for modelstring
27 | # Write model to a file:
28 | .temp = file("model.txt","w") ; writeLines(modelstring,con=.temp) ; close(.temp)
29 | # Load model file into BRugs and check its syntax:
30 | modelCheck( "model.txt" )
31 |
32 | #------------------------------------------------------------------------------
33 | # THE DATA.
34 |
35 | # Specify the data in a form that is compatible with BRugs model, as a list:
36 | N = 30
37 | z = 8
38 | datalist = list(
39 | y = c( rep(1,z) , rep(0,N-z) ) ,
40 | nFlip = N
41 | )
42 | # Get the data into BRugs:
43 | modelData( bugsData( datalist ) )
44 |
45 | #------------------------------------------------------------------------------
46 | # INTIALIZE THE CHAINS.
47 |
48 | nchain = 1
49 | modelCompile( numChains=nchain )
50 | modelGenInits()
51 |
52 | #------------------------------------------------------------------------------
53 | # RUN THE CHAINS.
54 |
55 | burninSteps = 1000
56 | modelUpdate( burninSteps )
57 | samplesSet( c("theta","nu","eta","mdlIdx") )
58 | nPerChain = 10000
59 | modelUpdate( nPerChain , thin=5 ) # takes nPerChain * thin steps
60 |
61 | #------------------------------------------------------------------------------
62 | # EXAMINE THE RESULTS.
63 |
64 | filenamebase = "ToyModelComp1"
65 |
66 | modelIdxSample = samplesSample( "mdlIdx" )
67 | pM1 = sum( modelIdxSample == 1 ) / length( modelIdxSample )
68 | pM2 = 1 - pM1
69 | string1 =paste("p(M1|D)=",round(pM1,3),sep="")
70 | string2 =paste("p(M2|D)=",round(pM2,3),sep="")
71 | windows(10,4)
72 | plot( 1:length(modelIdxSample) , modelIdxSample , type="l" ,
73 | xlab="Step in Markov chain" , ylab="Model Index (1, 2)" ,
74 | main=paste(string1,", ",string2,sep="") )
75 | dev.copy2eps(file=paste(filenamebase,"_mdlIdx",".eps",sep=""))
76 |
77 | thetaSampleM1 = samplesSample( "theta" )[ modelIdxSample == 1 ]
78 | thetaSampleM2 = samplesSample( "theta" )[ modelIdxSample == 2 ]
79 | source("plotPost.R")
80 | windows()
81 | layout( matrix(1:2,nrow=2) )
82 | h1 = plotPost( thetaSampleM1 , main="Post. theta for M1" , breaks=21 )
83 | h2 = plotPost( thetaSampleM2 , main="Post. theta for M2" , breaks=21 )
84 | dev.copy2eps(file=paste(filenamebase,"_theta",".eps",sep=""))
85 |
86 | nuSampleM1 = samplesSample( "nu" )[ modelIdxSample == 1 ]
87 | etaSampleM2 = samplesSample( "eta" )[ modelIdxSample == 2 ]
88 | windows()
89 | layout( matrix(1:2,nrow=2) )
90 | h1 = plotPost( nuSampleM1 ,
91 | main=bquote("p("*nu*"|D,M1), with p(M1|D)="*.(round(pM1,3))) ,
92 | breaks=21 , xlab=expression(nu) , xlim=c(-3,4) )
93 | h2 = plotPost( etaSampleM2 ,
94 | main=bquote("p("*eta*"|D,M2), with p(M2|D)="*.(round(pM2,3))) ,
95 | breaks=seq(0,50,.25) , xlab=expression(eta) , xlim=c(0,7) )
96 | dev.copy2eps(file=paste(filenamebase,"_nu_eta",".eps",sep=""))
--------------------------------------------------------------------------------
/1e/YmetricXsingleBrugs.R:
--------------------------------------------------------------------------------
1 | graphics.off()
2 | rm(list=ls(all=TRUE))
3 | library(BRugs) # Kruschke, J. K. (2010). Doing Bayesian data analysis:
4 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
5 | #------------------------------------------------------------------------------
6 | # THE MODEL.
7 | modelstring = "
8 | # BUGS model specification begins here...
9 | model {
10 | # Likelihood:
11 | for( i in 1 : N ) {
12 | y[i] ~ dnorm( mu , tau ) # tau is precision, not SD
13 | }
14 | # Prior:
15 | tau ~ dgamma( 0.01 , 0.01 )
16 | mu ~ dnorm( 0 , 1.0E-10 )
17 | }
18 | # ... end BUGS model specification
19 | " # close quote for modelstring
20 | writeLines(modelstring,con="model.txt")
21 | modelCheck( "model.txt" )
22 |
23 | #------------------------------------------------------------------------------
24 | # THE DATA.
25 |
26 | # Generate random data from known parameter values:
27 | set.seed(47405)
28 | trueM = 100
29 | trueSD = 15
30 | y = round( rnorm( n=500 , mean=trueM , sd=trueSD ) ) # R dnorm uses mean and SD
31 |
32 | datalist = list(
33 | y = y ,
34 | N = length( y )
35 | )
36 |
37 | # Get the data into BRugs: (default filename is data.txt).
38 | modelData( bugsData( datalist ) )
39 |
40 | #------------------------------------------------------------------------------
41 | # INTIALIZE THE CHAINS.
42 |
43 | nchain = 3
44 | modelCompile( numChains = nchain )
45 |
46 | automaticInit = F # TRUE or FALSE
47 | if ( automaticInit ) {
48 | modelGenInits() # automatically initialize chains from prior
49 | } else {
50 | genInitList <- function() { # manually initialize chains near the data
51 | list( mu = mean( datalist$y ) ,
52 | tau = 1 / sd( datalist$y )^2 )
53 | }
54 | for ( chainIdx in 1 : nchain ) {
55 | modelInits( bugsInits( genInitList ) )
56 | }
57 | }
58 |
59 | #------------------------------------------------------------------------------
60 | # RUN THE CHAINS
61 |
62 | # burn in
63 | BurnInSteps = 500
64 | modelUpdate( BurnInSteps )
65 | # actual samples
66 | samplesSet( c( "mu" , "tau" ) )
67 | stepsPerChain = 2000
68 | thinStep = 1
69 | modelUpdate( stepsPerChain , thin=thinStep )
70 |
71 | #------------------------------------------------------------------------------
72 | # EXAMINE THE RESULTS
73 |
74 | filenamert = "YmetricXsingleBrugs"
75 |
76 | source("plotChains.R")
77 | muSum = plotChains( "mu" , saveplots=F , filenamert )
78 | sigmaSum = plotChains( "tau" , saveplots=F , filenamert )
79 |
80 | muSample = samplesSample( "mu" )
81 | tauSample = samplesSample( "tau" )
82 | sigmaSample <- 1 / sqrt( tauSample ) # Convert precision to SD
83 |
84 | source("plotPost.R")
85 | windows()
86 | plotPost( muSample , xlab="mu" , breaks=30 , main="Posterior" )
87 | dev.copy2eps(file=paste(filenamert,"PostMu.eps",sep=""))
88 |
89 | nPts = length(muSample) ; nPtsForDisplay = min( nPts , 2000 )
90 | thinIdx = seq( 1 , nPts , nPts / nPtsForDisplay )
91 | windows()
92 | plot( muSample[thinIdx] , sigmaSample[thinIdx] , col="gray" ,
93 | xlab="mu" , ylab="sigma" , cex.lab=1.5 , main="Posterior" , log="y" )
94 | points( mean(muSample) , mean(sigmaSample) , pch="+" , cex=2 )
95 | text( mean(muSample) , mean(sigmaSample) ,
96 | bquote( .(round(mean(muSample),1)) *" "* .(round(mean(sigmaSample),1)) ),
97 | adj=c(.5,-0.5) )
98 | dev.copy2eps(file=paste(filenamert,"PostMuSigma.eps",sep=""))
99 |
100 | #------------------------------------------------------------------------------
--------------------------------------------------------------------------------
/1e/minNforHDIpower.R:
--------------------------------------------------------------------------------
1 | minNforHDIpower = function( genPriorMean , genPriorN ,
2 | HDImaxwid=NULL , nullVal=NULL , ROPE=c(nullVal,nullVal) ,
3 | desiredPower=0.8 , audPriorMean=0.5 , audPriorN=2 ,
4 | HDImass=0.95 , initSampSize=20 , verbose=T ) {
5 | if ( !xor( is.null(HDImaxwid) , is.null(nullVal) ) ) {
6 | stop("One and only one of HDImaxwid and nullVal must be specified.")
7 | }
8 | source("HDIofICDF.R")
9 | # Convert prior mean and N to a,b parameter values of beta distribution.
10 | genPriorA = genPriorMean * genPriorN
11 | genPriorB = ( 1.0 - genPriorMean ) * genPriorN
12 | audPriorA = audPriorMean * audPriorN
13 | audPriorB = ( 1.0 - audPriorMean ) * audPriorN
14 | # Initialize loop for incrementing sampleSize
15 | sampleSize = initSampSize
16 | notPowerfulEnough = TRUE
17 | # Increment sampleSize until desired power is achieved.
18 | while( notPowerfulEnough ) {
19 | zvec = 0:sampleSize # All possible z values for N flips.
20 | # Compute probability of each z value for data-generating prior.
21 | pzvec = exp( lchoose( sampleSize , zvec )
22 | + lbeta( zvec + genPriorA , sampleSize-zvec + genPriorB )
23 | - lbeta( genPriorA , genPriorB ) )
24 | # For each z value, compute HDI. hdiMat is min, max of HDI for each z.
25 | hdiMat = matrix( 0 , nrow=length(zvec) , ncol=2 )
26 | for ( zIdx in 1:length(zvec) ) {
27 | z = zvec[zIdx]
28 | hdiMat[zIdx,] = HDIofICDF( qbeta ,
29 | shape1 = z + audPriorA ,
30 | shape2 = sampleSize - z + audPriorB ,
31 | credMass = HDImass )
32 | }
33 | hdiWid = hdiMat[,2] - hdiMat[,1]
34 | if ( !is.null( HDImaxwid ) ) {
35 | powerHDI = sum( pzvec[ hdiWid < HDImaxwid ] )
36 | }
37 | if ( !is.null( nullVal ) ) {
38 | powerHDI = sum( pzvec[ hdiMat[,1] > ROPE[2] | hdiMat[,2] < ROPE[1] ] )
39 | }
40 | if ( verbose ) {
41 | cat( " For sample size = ", sampleSize , ", power = " , powerHDI ,
42 | "\n" , sep="" ) ; flush.console()
43 | }
44 | if ( powerHDI > desiredPower ) {
45 | notPowerfulEnough = FALSE
46 | } else {
47 | sampleSize = sampleSize + 1
48 | }
49 | } # End while( notPowerfulEnough )
50 | # Return the minimal sample size that achieved the desired power.
51 | return( sampleSize )
52 | } # end of function
--------------------------------------------------------------------------------
/1e/openGraphSaveGraph.R:
--------------------------------------------------------------------------------
1 | # openGraphSaveGraph.R
2 | # John K. Kruschke, January 29, 2013.
3 |
4 | openGraph = function( width=7 , height=7 , mag=1.0 , ... ) {
5 | if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
6 | X11( width=width*mag , height=height*mag , type="cairo" , ... )
7 | } else { # Windows OS
8 | windows( width=width*mag , height=height*mag , ... )
9 | }
10 | }
11 |
12 | saveGraph = function( file="saveGraphOutput" , type="pdf" , ... ) {
13 | if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
14 | if ( any( type == c("png","jpeg","jpg","tiff","bmp")) ) {
15 | sptype = type
16 | if ( type == "jpg" ) { sptype = "jpeg" }
17 | savePlot( file=paste(file,".",type,sep="") , type=sptype , ... )
18 | }
19 | if ( type == "pdf" ) {
20 | dev.copy2pdf(file=paste(file,".",type,sep="") , ... )
21 | }
22 | if ( type == "eps" ) {
23 | dev.copy2eps(file=paste(file,".",type,sep="") , ... )
24 | }
25 | } else { # Windows OS
26 | file=paste(file,".",type,sep="") # force explicit extension
27 | savePlot( file=file , type=type , ... )
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/1e/plotChains.R:
--------------------------------------------------------------------------------
1 | plotChains = function( nodename , saveplots=F , filenameroot="DeleteMe" ) {
2 | summarytable = samplesStats(nodename)
3 | show( summarytable )
4 | nCompon = NROW(summarytable)
5 | nPlotPerRow = 5
6 | nPlotRow = ceiling(nCompon/nPlotPerRow)
7 | nPlotCol = ceiling(nCompon/nPlotRow)
8 | windows(3.75*nPlotCol,3.5*nPlotRow)
9 | par( mar=c(4,4,3,1) , mgp=c(2,0.7,0) )
10 | samplesHistory( nodename , ask=F , mfrow=c(nPlotRow,nPlotCol) ,
11 | cex.lab=1.5 , cex.main=1.5 )
12 | if ( saveplots ) {
13 | dev.copy2eps( file=paste( filenameroot , toupper(nodename) ,
14 | "history.eps" , sep="" )) }
15 | windows(3.75*nPlotCol,3.5*nPlotRow)
16 | par( mar=c(4,4,3,1) , mgp=c(2,0.7,0) )
17 | samplesAutoC( nodename , chain=1 , ask=F , mfrow=c(nPlotRow,nPlotCol) ,
18 | cex.lab=1.5 , cex.main=1.5 )
19 | if ( saveplots ) {
20 | dev.copy2eps( file=paste( filenameroot , toupper(nodename) ,
21 | "autocorr.eps" , sep="" )) }
22 | windows(3.75*nPlotCol,3.5*nPlotRow)
23 | par( mar=c(4,4,3,1) , mgp=c(2,0.7,0) )
24 | samplesBgr( nodename , ask=F , mfrow=c(nPlotRow,nPlotCol) ,
25 | cex.lab=1.5 , cex.main=1.5 )
26 | if ( saveplots ) {
27 | dev.copy2eps( file=paste( filenameroot , toupper(nodename) ,
28 | "bgr.eps" , sep="" )) }
29 | return( summarytable )
30 | }
31 |
--------------------------------------------------------------------------------
/2e/AnovaShrinkageData.csv:
--------------------------------------------------------------------------------
1 | "Group","Y"
2 | "A",93.2041355866767
3 | "A",99.9697739894123
4 | "A",76.2171722634264
5 | "A",90.6089181604846
6 | "B",94.9947158689097
7 | "B",76.4507062962981
8 | "B",99.1635270585373
9 | "B",93.3910507762549
10 | "C",96.1568583861612
11 | "C",103.877907353428
12 | "C",81.4253735849949
13 | "C",86.5398606754162
14 | "D",82.863897645479
15 | "D",86.7219992770648
16 | "D",104.60813563522
17 | "D",97.8059674422363
18 | "E",102.646487985589
19 | "E",95.8917683505709
20 | "E",79.6168157996274
21 | "E",97.844927864213
22 | "F",103.959226513021
23 | "F",92.054451368933
24 | "F",82.1703854147245
25 | "F",101.815936703321
26 | "G",86.9230954840843
27 | "G",93.4855808303642
28 | "G",93.3071958960718
29 | "G",110.28412778948
30 | "H",98.0967997650696
31 | "H",101.255359092543
32 | "H",105.864417680294
33 | "H",82.7834234620937
34 | "I",84.5597033061792
35 | "I",97.8881317583269
36 | "I",101.06695028763
37 | "I",108.485214647864
38 | "J",96.7285266613481
39 | "J",113.3064770952
40 | "J",90.0038688827758
41 | "J",95.9611273606764
42 | "K",110.825878826
43 | "K",99.0604804763229
44 | "K",103.213032722916
45 | "K",86.9006079747618
46 | "L",110.280236919564
47 | "L",95.3174402511083
48 | "L",108.558353218427
49 | "L",89.8439696109001
50 | "M",103.84557350607
51 | "M",99.9407616370772
52 | "M",114.19671599823
53 | "M",90.0169488586222
54 | "N",103.338369482135
55 | "N",89.0850662047118
56 | "N",112.443331524452
57 | "N",107.133232788701
58 | "O",90.2478573579484
59 | "O",107.806165720453
60 | "O",113.817080057715
61 | "O",104.128896863883
62 | "P",96.5006379421743
63 | "P",105.716614520461
64 | "P",98.9676212369062
65 | "P",118.815126300459
66 | "Q",97.1227394709454
67 | "Q",120.228025750305
68 | "Q",104.814950325581
69 | "Q",101.834284453169
70 | "R",109.498257751304
71 | "R",119.904768752541
72 | "R",97.2249584853789
73 | "R",101.372015010776
74 | "S",109.861434536303
75 | "S",95.6280952468599
76 | "S",106.613095311758
77 | "S",119.89737490508
78 | "T",95.3328987246139
79 | "T",118.489854030809
80 | "T",113.774542080761
81 | "T",108.402705163817
82 | "U",108.566893721221
83 | "U",100.35677642245
84 | "U",124.012004196288
85 | "U",107.064325660041
86 |
--------------------------------------------------------------------------------
/2e/BernBetaExample.R:
--------------------------------------------------------------------------------
1 | source("DBDA2E-utilities.R") # Load definitions of graphics functions etc.
2 | source("BernBeta.R") # Load the definition of the BernBeta function
3 |
4 | # Specify the prior:
5 | t = 0.75 # Specify the prior MODE.
6 | n = 25 # Specify the effective prior sample size.
7 | a = t*(n-2) + 1 # Convert to beta shape parameter a.
8 | b = (1-t)*(n-2) + 1 # Convert to beta shape parameter b.
9 |
10 | Prior = c(a,b) # Specify Prior as vector with the two shape parameters.
11 |
12 | # Specify the data:
13 | N = 20 # The total number of flips.
14 | z = 17 # The number of heads.
15 | Data = c(rep(0,N-z),rep(1,z)) # Convert N and z into vector of 0's and 1's.
16 |
17 | openGraph(width=5,height=7)
18 | posterior = BernBeta( priorBetaAB=Prior, Data=Data , plotType="Bars" ,
19 | showCentTend="Mode" , showHDI=TRUE , showpD=FALSE )
20 | saveGraph(file="BernBetaExample",type="png")
21 |
--------------------------------------------------------------------------------
/2e/BugsRatsData.csv:
--------------------------------------------------------------------------------
1 | "Subj","Day","Weight"
2 | 1,8,151
3 | 1,15,199
4 | 1,22,246
5 | 1,29,283
6 | 1,36,320
7 | 2,8,145
8 | 2,15,199
9 | 2,22,249
10 | 2,29,293
11 | 2,36,354
12 | 3,8,147
13 | 3,15,214
14 | 3,22,263
15 | 3,29,312
16 | 3,36,328
17 | 4,8,155
18 | 4,15,200
19 | 4,22,237
20 | 4,29,272
21 | 4,36,297
22 | 5,8,135
23 | 5,15,188
24 | 5,22,230
25 | 5,29,280
26 | 5,36,323
27 | 6,8,159
28 | 6,15,210
29 | 6,22,252
30 | 6,29,298
31 | 6,36,331
32 | 7,8,141
33 | 7,15,189
34 | 7,22,231
35 | 7,29,275
36 | 7,36,305
37 | 8,8,159
38 | 8,15,201
39 | 8,22,248
40 | 8,29,297
41 | 8,36,338
42 | 9,8,177
43 | 9,15,236
44 | 9,22,285
45 | 9,29,350
46 | 9,36,376
47 | 10,8,134
48 | 10,15,182
49 | 10,22,220
50 | 10,29,260
51 | 10,36,296
52 | 11,8,160
53 | 11,15,208
54 | 11,22,261
55 | 11,29,313
56 | 11,36,352
57 | 12,8,143
58 | 12,15,188
59 | 12,22,220
60 | 12,29,273
61 | 12,36,314
62 | 13,8,154
63 | 13,15,200
64 | 13,22,244
65 | 13,29,289
66 | 13,36,325
67 | 14,8,171
68 | 14,15,221
69 | 14,22,270
70 | 14,29,326
71 | 14,36,358
72 | 15,8,163
73 | 15,15,216
74 | 15,22,242
75 | 15,29,281
76 | 15,36,312
77 | 16,8,160
78 | 16,15,207
79 | 16,22,248
80 | 16,29,288
81 | 16,36,324
82 | 17,8,142
83 | 17,15,187
84 | 17,22,234
85 | 17,29,280
86 | 17,36,316
87 | 18,8,156
88 | 18,15,203
89 | 18,22,243
90 | 18,29,283
91 | 18,36,317
92 | 19,8,157
93 | 19,15,212
94 | 19,22,259
95 | 19,29,307
96 | 19,36,336
97 | 20,8,152
98 | 20,15,203
99 | 20,22,246
100 | 20,29,286
101 | 20,36,321
102 | 21,8,154
103 | 21,15,205
104 | 21,22,253
105 | 21,29,298
106 | 21,36,334
107 | 22,8,139
108 | 22,15,190
109 | 22,22,225
110 | 22,29,267
111 | 22,36,302
112 | 23,8,146
113 | 23,15,191
114 | 23,22,229
115 | 23,29,272
116 | 23,36,302
117 | 24,8,157
118 | 24,15,211
119 | 24,22,250
120 | 24,29,285
121 | 24,36,323
122 | 25,8,132
123 | 25,15,185
124 | 25,22,237
125 | 25,29,286
126 | 25,36,331
127 | 26,8,160
128 | 26,15,207
129 | 26,22,257
130 | 26,29,303
131 | 26,36,345
132 | 27,8,169
133 | 27,15,216
134 | 27,22,261
135 | 27,29,295
136 | 27,36,333
137 | 28,8,157
138 | 28,15,205
139 | 28,22,248
140 | 28,29,289
141 | 28,36,316
142 | 29,8,137
143 | 29,15,180
144 | 29,22,219
145 | 29,29,258
146 | 29,36,291
147 | 30,8,153
148 | 30,15,200
149 | 30,22,244
150 | 30,29,286
151 | 30,36,324
152 |
--------------------------------------------------------------------------------
/2e/CrimeDrink.csv:
--------------------------------------------------------------------------------
1 | "Count","Crime","Drink"
2 | 50,"Arson","Drinker"
3 | 88,"Rape","Drinker"
4 | 155,"Violence","Drinker"
5 | 379,"Theft","Drinker"
6 | 18,"Coining","Drinker"
7 | 63,"Fraud","Drinker"
8 | 43,"Arson","Nondrink"
9 | 62,"Rape","Nondrink"
10 | 110,"Violence","Nondrink"
11 | 300,"Theft","Nondrink"
12 | 14,"Coining","Nondrink"
13 | 144,"Fraud","Nondrink"
14 |
--------------------------------------------------------------------------------
/2e/FourByFourCount.csv:
--------------------------------------------------------------------------------
1 | A,B,Count
2 | A1,B1,2
3 | A1,B2,2
4 | A1,B3,1
5 | A1,B4,1
6 | A2,B1,2
7 | A2,B2,2
8 | A2,B3,1
9 | A2,B4,1
10 | A3,B1,1
11 | A3,B2,1
12 | A3,B3,2
13 | A3,B4,2
14 | A4,B1,1
15 | A4,B2,1
16 | A4,B3,2
17 | A4,B4,2
18 |
--------------------------------------------------------------------------------
/2e/FruitflyDataReduced.csv:
--------------------------------------------------------------------------------
1 | Longevity,CompanionNumber,Thorax
2 | 35,Pregnant8,0.64
3 | 37,Pregnant8,0.68
4 | 49,Pregnant8,0.68
5 | 46,Pregnant8,0.72
6 | 63,Pregnant8,0.72
7 | 39,Pregnant8,0.76
8 | 46,Pregnant8,0.76
9 | 56,Pregnant8,0.76
10 | 63,Pregnant8,0.76
11 | 65,Pregnant8,0.76
12 | 56,Pregnant8,0.8
13 | 65,Pregnant8,0.8
14 | 70,Pregnant8,0.8
15 | 63,Pregnant8,0.84
16 | 65,Pregnant8,0.84
17 | 70,Pregnant8,0.84
18 | 77,Pregnant8,0.84
19 | 81,Pregnant8,0.84
20 | 86,Pregnant8,0.84
21 | 70,Pregnant8,0.88
22 | 70,Pregnant8,0.88
23 | 77,Pregnant8,0.92
24 | 77,Pregnant8,0.92
25 | 81,Pregnant8,0.92
26 | 77,Pregnant8,0.94
27 | 40,None0,0.64
28 | 37,None0,0.7
29 | 44,None0,0.72
30 | 47,None0,0.72
31 | 47,None0,0.72
32 | 47,None0,0.76
33 | 68,None0,0.78
34 | 47,None0,0.8
35 | 54,None0,0.84
36 | 61,None0,0.84
37 | 71,None0,0.84
38 | 75,None0,0.84
39 | 89,None0,0.84
40 | 58,None0,0.88
41 | 59,None0,0.88
42 | 62,None0,0.88
43 | 79,None0,0.88
44 | 96,None0,0.88
45 | 58,None0,0.92
46 | 62,None0,0.92
47 | 70,None0,0.92
48 | 72,None0,0.92
49 | 75,None0,0.92
50 | 96,None0,0.92
51 | 75,None0,0.94
52 | 46,Pregnant1,0.64
53 | 42,Pregnant1,0.68
54 | 65,Pregnant1,0.72
55 | 46,Pregnant1,0.76
56 | 58,Pregnant1,0.76
57 | 42,Pregnant1,0.8
58 | 48,Pregnant1,0.8
59 | 58,Pregnant1,0.8
60 | 50,Pregnant1,0.82
61 | 80,Pregnant1,0.82
62 | 63,Pregnant1,0.84
63 | 65,Pregnant1,0.84
64 | 70,Pregnant1,0.84
65 | 70,Pregnant1,0.84
66 | 72,Pregnant1,0.84
67 | 97,Pregnant1,0.84
68 | 46,Pregnant1,0.88
69 | 56,Pregnant1,0.88
70 | 70,Pregnant1,0.88
71 | 70,Pregnant1,0.88
72 | 72,Pregnant1,0.88
73 | 76,Pregnant1,0.88
74 | 90,Pregnant1,0.88
75 | 76,Pregnant1,0.92
76 | 92,Pregnant1,0.92
77 | 21,Virgin1,0.68
78 | 40,Virgin1,0.68
79 | 44,Virgin1,0.72
80 | 54,Virgin1,0.76
81 | 36,Virgin1,0.78
82 | 40,Virgin1,0.8
83 | 56,Virgin1,0.8
84 | 60,Virgin1,0.8
85 | 48,Virgin1,0.84
86 | 53,Virgin1,0.84
87 | 60,Virgin1,0.84
88 | 60,Virgin1,0.84
89 | 65,Virgin1,0.84
90 | 68,Virgin1,0.84
91 | 60,Virgin1,0.88
92 | 81,Virgin1,0.88
93 | 81,Virgin1,0.88
94 | 48,Virgin1,0.9
95 | 48,Virgin1,0.9
96 | 56,Virgin1,0.9
97 | 68,Virgin1,0.9
98 | 75,Virgin1,0.9
99 | 81,Virgin1,0.9
100 | 48,Virgin1,0.92
101 | 68,Virgin1,0.92
102 | 16,Virgin8,0.64
103 | 19,Virgin8,0.64
104 | 19,Virgin8,0.68
105 | 32,Virgin8,0.72
106 | 33,Virgin8,0.72
107 | 33,Virgin8,0.74
108 | 30,Virgin8,0.76
109 | 42,Virgin8,0.76
110 | 42,Virgin8,0.76
111 | 33,Virgin8,0.78
112 | 26,Virgin8,0.8
113 | 30,Virgin8,0.8
114 | 40,Virgin8,0.82
115 | 54,Virgin8,0.82
116 | 34,Virgin8,0.84
117 | 34,Virgin8,0.84
118 | 47,Virgin8,0.84
119 | 47,Virgin8,0.84
120 | 42,Virgin8,0.88
121 | 47,Virgin8,0.88
122 | 54,Virgin8,0.88
123 | 54,Virgin8,0.88
124 | 56,Virgin8,0.88
125 | 60,Virgin8,0.88
126 | 44,Virgin8,0.92
127 |
--------------------------------------------------------------------------------
/2e/Guber1999data.csv:
--------------------------------------------------------------------------------
1 | State,Spend,StuTeaRat,Salary,PrcntTake,SATV,SATM,SATT
2 | Alabama,4.405,17.2,31.144,8,491,538,1029
3 | Alaska,8.963,17.6,47.951,47,445,489,934
4 | Arizona,4.778,19.3,32.175,27,448,496,944
5 | Arkansas,4.459,17.1,28.934,6,482,523,1005
6 | California,4.992,24,41.078,45,417,485,902
7 | Colorado,5.443,18.4,34.571,29,462,518,980
8 | Connecticut,8.817,14.4,50.045,81,431,477,908
9 | Delaware,7.03,16.6,39.076,68,429,468,897
10 | Florida,5.718,19.1,32.588,48,420,469,889
11 | Georgia,5.193,16.3,32.291,65,406,448,854
12 | Hawaii,6.078,17.9,38.518,57,407,482,889
13 | Idaho,4.21,19.1,29.783,15,468,511,979
14 | Illinois,6.136,17.3,39.431,13,488,560,1048
15 | Indiana,5.826,17.5,36.785,58,415,467,882
16 | Iowa,5.483,15.8,31.511,5,516,583,1099
17 | Kansas,5.817,15.1,34.652,9,503,557,1060
18 | Kentucky,5.217,17,32.257,11,477,522,999
19 | Louisiana,4.761,16.8,26.461,9,486,535,1021
20 | Maine,6.428,13.8,31.972,68,427,469,896
21 | Maryland,7.245,17,40.661,64,430,479,909
22 | Massachusetts,7.287,14.8,40.795,80,430,477,907
23 | Michigan,6.994,20.1,41.895,11,484,549,1033
24 | Minnesota,6,17.5,35.948,9,506,579,1085
25 | Mississippi,4.08,17.5,26.818,4,496,540,1036
26 | Missouri,5.383,15.5,31.189,9,495,550,1045
27 | Montana,5.692,16.3,28.785,21,473,536,1009
28 | Nebraska,5.935,14.5,30.922,9,494,556,1050
29 | Nevada,5.16,18.7,34.836,30,434,483,917
30 | New Hampshire,5.859,15.6,34.72,70,444,491,935
31 | New Jersey,9.774,13.8,46.087,70,420,478,898
32 | New Mexico,4.586,17.2,28.493,11,485,530,1015
33 | New York,9.623,15.2,47.612,74,419,473,892
34 | North Carolina,5.077,16.2,30.793,60,411,454,865
35 | North Dakota,4.775,15.3,26.327,5,515,592,1107
36 | Ohio,6.162,16.6,36.802,23,460,515,975
37 | Oklahoma,4.845,15.5,28.172,9,491,536,1027
38 | Oregon,6.436,19.9,38.555,51,448,499,947
39 | Pennsylvania,7.109,17.1,44.51,70,419,461,880
40 | Rhode Island,7.469,14.7,40.729,70,425,463,888
41 | South Carolina,4.797,16.4,30.279,58,401,443,844
42 | South Dakota,4.775,14.4,25.994,5,505,563,1068
43 | Tennessee,4.388,18.6,32.477,12,497,543,1040
44 | Texas,5.222,15.7,31.223,47,419,474,893
45 | Utah,3.656,24.3,29.082,4,513,563,1076
46 | Vermont,6.75,13.8,35.406,68,429,472,901
47 | Virginia,5.327,14.6,33.987,65,428,468,896
48 | Washington,5.906,20.2,36.151,48,443,494,937
49 | West Virginia,6.107,14.8,31.944,17,448,484,932
50 | Wisconsin,6.93,15.9,37.746,9,501,572,1073
51 | Wyoming,6.16,14.9,31.285,10,476,525,1001
52 |
--------------------------------------------------------------------------------
/2e/HGN.csv:
--------------------------------------------------------------------------------
1 | Hair,Gender,Number,Name,Group
2 | black,M,2,Alex,1
3 | brown,F,4,Betty,1
4 | blond,F,3,Carla,1
5 | black,F,7,Diane,2
6 | black,M,1,Edward,2
7 | red,M,7,Frank,2
8 | brown,F,10,Gabrielle,2
9 |
--------------------------------------------------------------------------------
/2e/HairEyeColor.csv:
--------------------------------------------------------------------------------
1 | Hair,Eye,Count
2 | Black,Blue,20
3 | Black,Brown,68
4 | Black,Green,5
5 | Black,Hazel,15
6 | Blond,Blue,94
7 | Blond,Brown,7
8 | Blond,Green,16
9 | Blond,Hazel,10
10 | Brown,Blue,84
11 | Brown,Brown,119
12 | Brown,Green,29
13 | Brown,Hazel,54
14 | Red,Blue,17
15 | Red,Brown,26
16 | Red,Green,14
17 | Red,Hazel,14
18 |
--------------------------------------------------------------------------------
/2e/HierLinRegressData.csv:
--------------------------------------------------------------------------------
1 | "Subj","X","Y"
2 | 1,60.2,145.6
3 | 1,61.5,157.3
4 | 1,61.7,165.6
5 | 1,62.3,158.8
6 | 1,67.6,196.1
7 | 1,69.2,183.9
8 | 2,53.7,165
9 | 2,60.1,166.9
10 | 2,60.5,179
11 | 2,62.3,196.2
12 | 2,63,192.3
13 | 2,64,200.7
14 | 2,64.1,187.8
15 | 2,66.7,158.9
16 | 2,67.1,178.2
17 | 3,63.5,161.4
18 | 3,65.4,98.8
19 | 3,69.6,145.9
20 | 3,71,151.6
21 | 3,77.6,144.8
22 | 3,79.1,140.4
23 | 3,81.1,165.1
24 | 4,65,172.2
25 | 4,69.8,191.4
26 | 5,65.1,119
27 | 5,68.5,168.6
28 | 5,71.8,136.7
29 | 5,76.6,119.7
30 | 5,83.3,189
31 | 6,69.9,70
32 | 6,71.3,86.4
33 | 6,75,93.6
34 | 6,75.4,113.8
35 | 6,76.9,122.2
36 | 6,77.4,120.8
37 | 6,79.1,161.8
38 | 6,86.2,188.1
39 | 7,67.2,144.5
40 | 7,73.4,187.3
41 | 7,77.3,171.9
42 | 8,59.7,91.9
43 | 8,62.3,131
44 | 8,65.3,157.7
45 | 8,66.2,162.7
46 | 8,74.1,201.8
47 | 8,74.8,142.6
48 | 9,59.1,125.4
49 | 9,63.3,122.3
50 | 9,68.5,122.5
51 | 9,70.1,141.3
52 | 9,73.9,167.6
53 | 10,65.5,101.8
54 | 10,68.5,127.3
55 | 10,68.7,119.2
56 | 10,68.9,124.4
57 | 10,80.5,124.1
58 | 10,83.3,146.9
59 | 11,62,147.5
60 | 11,62.2,144.4
61 | 11,62.5,167.4
62 | 11,63.4,193.3
63 | 11,65.1,172.4
64 | 11,68,196.6
65 | 12,63.6,120.2
66 | 12,71.7,160
67 | 12,72,165.3
68 | 12,75.4,158.7
69 | 13,56,203.4
70 | 13,57.8,152.1
71 | 13,57.9,157.9
72 | 13,57.9,167.2
73 | 13,60,147.7
74 | 13,66.9,240.4
75 | 14,50.8,131.4
76 | 14,56.3,143.7
77 | 14,57.3,159.5
78 | 14,62.4,198.3
79 | 14,62.6,194.7
80 | 14,66.4,174
81 | 14,67.9,189.4
82 | 15,59.6,146.6
83 | 15,66,153.7
84 | 16,56.3,146.6
85 | 16,64.2,144.6
86 | 16,65.9,159.4
87 | 16,69.4,163.8
88 | 16,73.3,202.6
89 | 17,63.6,153.6
90 | 17,63.8,146.8
91 | 17,64.8,137.8
92 | 17,65.9,145
93 | 17,68.9,166.1
94 | 17,72.3,154
95 | 17,72.8,189.7
96 | 17,76.2,184.8
97 | 17,76.6,172.5
98 | 18,61.8,126.4
99 | 18,61.9,94.2
100 | 18,63.2,97.7
101 | 18,70.2,141.9
102 | 18,70.4,117.6
103 | 18,71.2,133.9
104 | 18,71.9,156
105 | 18,75.4,162.6
106 | 18,75.5,184.3
107 | 19,66.5,132.6
108 | 19,68.2,202
109 | 20,63.6,152.4
110 | 20,64.5,202.1
111 | 20,64.6,171.9
112 | 20,68.2,146.5
113 | 20,70.4,221.9
114 | 21,49.1,114.8
115 | 21,57.5,172.7
116 | 21,60.4,201.7
117 | 21,63.9,208.7
118 | 22,58.3,94.5
119 | 22,63,91.5
120 | 22,65.3,116.1
121 | 22,66.3,137.8
122 | 22,66.5,134.8
123 | 22,67.4,152.4
124 | 22,72.1,152.6
125 | 23,61.9,104.5
126 | 23,62.5,111.8
127 | 23,63.1,129.8
128 | 23,63.7,99.8
129 | 23,64,124.6
130 | 23,66.7,175.6
131 | 23,81.8,203.6
132 | 24,49.1,153.6
133 | 25,86.2,153.6
134 |
--------------------------------------------------------------------------------
/2e/HtWtData110.csv:
--------------------------------------------------------------------------------
1 | "male","height","weight"
2 | 0,63.2,168.7
3 | 0,68.7,169.8
4 | 0,64.8,176.6
5 | 0,67.9,246.8
6 | 1,68.9,151.6
7 | 1,67.8,158
8 | 1,68.2,168.6
9 | 0,64.8,137.2
10 | 1,64.3,177
11 | 0,64.7,128
12 | 1,66.9,168.4
13 | 1,66.9,136.2
14 | 1,67.1,160.3
15 | 1,70.2,233.9
16 | 1,67.4,171.7
17 | 1,71.1,185.5
18 | 0,63.4,177.6
19 | 1,66.9,132.9
20 | 0,71,140.1
21 | 1,70.4,151.9
22 | 0,59.5,147.2
23 | 1,70.4,159
24 | 0,61.5,113
25 | 1,74.5,194.5
26 | 0,65.3,145.1
27 | 1,68.8,196.5
28 | 0,67.2,148.9
29 | 1,68.7,132.9
30 | 0,60,168.4
31 | 0,62.5,146.2
32 | 1,72,236.4
33 | 1,67.9,140
34 | 1,65.1,156.2
35 | 1,63.5,178.7
36 | 1,68.2,147.5
37 | 0,64.6,97.7
38 | 1,68.1,189.6
39 | 0,66.2,221.9
40 | 0,62.8,168.1
41 | 0,65.3,143.1
42 | 0,65.8,217.7
43 | 0,68.7,133.2
44 | 0,63.8,96.5
45 | 1,70.6,270.6
46 | 0,61.5,137.2
47 | 0,61.9,124.2
48 | 0,65.1,128.3
49 | 1,68.7,203.6
50 | 0,57.6,132.4
51 | 1,66.3,189.4
52 | 1,69,174
53 | 0,63.4,163.3
54 | 1,69.5,183.5
55 | 1,67.8,193.8
56 | 0,61.6,119.7
57 | 1,71.2,157.4
58 | 1,67.4,146.1
59 | 0,66.1,128.3
60 | 1,70.7,179.1
61 | 0,67,140
62 | 1,66.8,202.2
63 | 1,69.9,169.4
64 | 0,57.7,122.8
65 | 0,62.5,248.5
66 | 1,66.6,154.4
67 | 0,60.6,140.2
68 | 1,70.4,141.6
69 | 0,66.4,144.4
70 | 0,62.3,116.2
71 | 1,73.3,175
72 | 0,67.2,141.9
73 | 0,62.8,156.3
74 | 0,64.8,164.6
75 | 0,59.5,122
76 | 1,70.5,227.2
77 | 1,71.2,143.5
78 | 0,64.6,115.8
79 | 1,71.7,164.7
80 | 0,62.4,125.1
81 | 1,72.3,147
82 | 1,68.4,188.5
83 | 0,62.8,102.5
84 | 1,72.7,198.2
85 | 1,70.2,164.7
86 | 0,63.7,109.5
87 | 1,66,196.2
88 | 0,58.8,103.5
89 | 0,60.1,115.2
90 | 1,68.8,128.9
91 | 1,66.8,191.9
92 | 0,61.2,95.5
93 | 0,62.8,175
94 | 0,66.4,138.6
95 | 1,71.8,220.5
96 | 0,70.4,149.4
97 | 0,65.4,121.6
98 | 1,71.8,171.8
99 | 1,70,158.1
100 | 0,66.8,200.9
101 | 0,62.3,120.6
102 | 0,63.7,121.3
103 | 1,68.4,152
104 | 0,62.3,127.9
105 | 0,62.2,116.8
106 | 0,67.4,136.4
107 | 1,69.9,174.5
108 | 1,73.2,221.6
109 | 0,61.9,160.6
110 | 0,66.1,117.1
111 | 0,63.8,122.1
112 |
--------------------------------------------------------------------------------
/2e/HtWtData30.csv:
--------------------------------------------------------------------------------
1 | "male","height","weight"
2 | 0,64,136.4
3 | 0,62.3,215.1
4 | 1,67.9,173.6
5 | 0,64.2,117.3
6 | 0,64.8,123.3
7 | 0,57.5,96.5
8 | 0,65.6,178.3
9 | 1,70.2,191.1
10 | 0,63.9,158
11 | 1,71.1,193.9
12 | 1,66.5,127.1
13 | 0,68.1,147.9
14 | 0,62.9,119
15 | 1,75.1,204.4
16 | 1,64.6,143.4
17 | 1,69.2,124.4
18 | 1,68.1,140.9
19 | 1,72.6,164.7
20 | 0,63.2,139.8
21 | 0,64.1,110.2
22 | 0,64.1,134.1
23 | 1,71.5,193.6
24 | 1,76,180
25 | 1,69.7,155
26 | 1,73.3,188.2
27 | 0,61.7,187.4
28 | 0,66.4,139.2
29 | 0,65.7,147.9
30 | 1,68.3,178.6
31 | 0,66.9,111.1
32 |
--------------------------------------------------------------------------------
/2e/HtWtDataGenerator.R:
--------------------------------------------------------------------------------
1 | HtWtDataGenerator = function( nSubj , rndsd=NULL , maleProb=0.50 ) {
2 | # Random height, weight generator for males and females. Uses parameters from
3 | # Brainard, J. & Burmaster, D. E. (1992). Bivariate distributions for height and
4 | # weight of men and women in the United States. Risk Analysis, 12(2), 267-275.
5 | # Kruschke, J. K. (2011). Doing Bayesian data analysis:
6 | # A Tutorial with R and BUGS. Academic Press / Elsevier.
7 | # Kruschke, J. K. (2014). Doing Bayesian data analysis, 2nd Edition:
8 | # A Tutorial with R, JAGS and Stan. Academic Press / Elsevier.
9 |
10 | require(MASS)
11 |
12 | # Specify parameters of multivariate normal (MVN) distributions.
13 | # Men:
14 | HtMmu = 69.18
15 | HtMsd = 2.87
16 | lnWtMmu = 5.14
17 | lnWtMsd = 0.17
18 | Mrho = 0.42
19 | Mmean = c( HtMmu , lnWtMmu )
20 | Msigma = matrix( c( HtMsd^2 , Mrho * HtMsd * lnWtMsd ,
21 | Mrho * HtMsd * lnWtMsd , lnWtMsd^2 ) , nrow=2 )
22 | # Women cluster 1:
23 | HtFmu1 = 63.11
24 | HtFsd1 = 2.76
25 | lnWtFmu1 = 5.06
26 | lnWtFsd1 = 0.24
27 | Frho1 = 0.41
28 | prop1 = 0.46
29 | Fmean1 = c( HtFmu1 , lnWtFmu1 )
30 | Fsigma1 = matrix( c( HtFsd1^2 , Frho1 * HtFsd1 * lnWtFsd1 ,
31 | Frho1 * HtFsd1 * lnWtFsd1 , lnWtFsd1^2 ) , nrow=2 )
32 | # Women cluster 2:
33 | HtFmu2 = 64.36
34 | HtFsd2 = 2.49
35 | lnWtFmu2 = 4.86
36 | lnWtFsd2 = 0.14
37 | Frho2 = 0.44
38 | prop2 = 1 - prop1
39 | Fmean2 = c( HtFmu2 , lnWtFmu2 )
40 | Fsigma2 = matrix( c( HtFsd2^2 , Frho2 * HtFsd2 * lnWtFsd2 ,
41 | Frho2 * HtFsd2 * lnWtFsd2 , lnWtFsd2^2 ) , nrow=2 )
42 |
43 | # Randomly generate data values from those MVN distributions.
44 | if ( !is.null( rndsd ) ) { set.seed( rndsd ) }
45 | datamatrix = matrix( 0 , nrow=nSubj , ncol=3 )
46 | colnames(datamatrix) = c( "male" , "height" , "weight" )
47 | maleval = 1 ; femaleval = 0 # arbitrary coding values
48 | for ( i in 1:nSubj ) {
49 | # Flip coin to decide sex
50 | sex = sample( c(maleval,femaleval) , size=1 , replace=TRUE ,
51 | prob=c(maleProb,1-maleProb) )
52 | if ( sex == maleval ) { datum = mvrnorm(n = 1, mu=Mmean, Sigma=Msigma ) }
53 | if ( sex == femaleval ) {
54 | Fclust = sample( c(1,2) , size=1 , replace=TRUE , prob=c(prop1,prop2) )
55 | if ( Fclust == 1 ) { datum = mvrnorm(n = 1, mu=Fmean1, Sigma=Fsigma1 ) }
56 | if ( Fclust == 2 ) { datum = mvrnorm(n = 1, mu=Fmean2, Sigma=Fsigma2 ) }
57 | }
58 | datamatrix[ i , ] = c( sex , round( c( datum[1] , exp( datum[2] ) ) , 1 ) )
59 | }
60 |
61 | return( datamatrix )
62 | } # end function
--------------------------------------------------------------------------------
/2e/IntegralOfDensity.R:
--------------------------------------------------------------------------------
1 | source("DBDA2E-utilities.R")
2 | # Graph of normal probability density function, with comb of intervals.
3 | meanval = 0.0 # Specify mean of distribution.
4 | sdval = 0.2 # Specify standard deviation of distribution.
5 | xlow = meanval - 3.5*sdval # Specify low end of x-axis.
6 | xhigh = meanval + 3.5*sdval # Specify high end of x-axis.
7 | dx = sdval/10 # Specify interval width on x-axis
8 | # Specify comb of points along the x axis:
9 | x = seq( from = xlow , to = xhigh , by = dx )
10 | # Compute y values, i.e., probability density at each value of x:
11 | y = ( 1/(sdval*sqrt(2*pi)) ) * exp( -.5 * ((x-meanval)/sdval)^2 )
12 | # Plot the function. "plot" draws the intervals. "lines" draws the bell curve.
13 | openGraph(width=7,height=5)
14 | plot( x , y , type="h" , lwd=1 , cex.axis=1.5
15 | , xlab="x" , ylab="p(x)" , cex.lab=1.5 ,
16 | , main="Normal Probability Density" , cex.main=1.5 )
17 | lines( x , y , lwd=3 , col="skyblue" )
18 | # Approximate the integral as the sum of width * height for each interval.
19 | area = sum( dx * y )
20 | # Display info in the graph.
21 | text( meanval-sdval , .9*max(y) , bquote( paste(mu ," = " ,.(meanval)) )
22 | , adj=c(1,.5) , cex=1.5 )
23 | text( meanval-sdval , .75*max(y) , bquote( paste(sigma ," = " ,.(sdval)) )
24 | , adj=c(1,.5) , cex=1.5 )
25 | text( meanval+sdval , .9*max(y) , bquote( paste(Delta , "x = " ,.(dx)) )
26 | , adj=c(0,.5) , cex=1.5 )
27 | text( meanval+sdval , .75*max(y) ,
28 | bquote(
29 | paste( sum(,x,) , " " , Delta , "x p(x) = " , .(signif(area,3)) )
30 | ) , adj=c(0,.5) , cex=1.5 )
31 | # Save the plot to an EPS file.
32 | saveGraph( file = "IntegralOfDensity" , type="eps" )
--------------------------------------------------------------------------------
/2e/Jags-ExampleScript.R:
--------------------------------------------------------------------------------
1 | # Jags-ExampleScript.R
2 | # Accompanies the book:
3 | # Kruschke, J. K. (2014). Doing Bayesian Data Analysis:
4 | # A Tutorial with R, JAGS, and Stan. 2nd Edition. Academic Press / Elsevier.
5 |
6 | # Optional generic preliminaries:
7 | graphics.off() # This closes all of R's graphics windows.
8 | rm(list=ls()) # Careful! This clears all of R's memory!
9 |
10 | # Load the functions used below:
11 | source("DBDA2E-utilities.R") # Must be in R's current working directory.
12 | require(rjags) # Must have previously installed package rjags.
13 |
14 | fileNameRoot="Jags-ExampleScript" # For output file names.
15 |
16 | # Load the data:
17 | myData = read.csv("z15N50.csv") # Read data file; must be in curr. work. dir.
18 | y = myData$y # The y values are in the column named y.
19 | Ntotal = length(y) # Compute the total number of flips.
20 | dataList = list( # Put the information into a list.
21 | y = y ,
22 | Ntotal = Ntotal
23 | )
24 |
25 | # Define the model:
26 | modelString = "
27 | model {
28 | for ( i in 1:Ntotal ) {
29 | y[i] ~ dbern( theta )
30 | }
31 | theta ~ dbeta( 1 , 1 )
32 | }
33 | " # close quote for modelString
34 | writeLines( modelString , con="TEMPmodel.txt" )
35 |
36 | # Initialize the chains based on MLE of data.
37 | # Option: Use single initial value for all chains:
38 | # thetaInit = sum(y)/length(y)
39 | # initsList = list( theta=thetaInit )
40 | # Option: Use function that generates random values for each chain:
41 | initsList = function() {
42 | resampledY = sample( y , replace=TRUE )
43 | thetaInit = sum(resampledY)/length(resampledY)
44 | thetaInit = 0.001+0.998*thetaInit # keep away from 0,1
45 | return( list( theta=thetaInit ) )
46 | }
47 |
48 | # Run the chains:
49 | jagsModel = jags.model( file="TEMPmodel.txt" , data=dataList , inits=initsList ,
50 | n.chains=3 , n.adapt=500 )
51 | update( jagsModel , n.iter=500 )
52 | codaSamples = coda.samples( jagsModel , variable.names=c("theta") ,
53 | n.iter=3334 )
54 | save( codaSamples , file=paste0(fileNameRoot,"Mcmc.Rdata") )
55 |
56 | # Examine the chains:
57 | # Convergence diagnostics:
58 | diagMCMC( codaObject=codaSamples , parName="theta" )
59 | saveGraph( file=paste0(fileNameRoot,"ThetaDiag") , type="eps" )
60 | # Posterior descriptives:
61 | openGraph(height=3,width=4)
62 | par( mar=c(3.5,0.5,2.5,0.5) , mgp=c(2.25,0.7,0) )
63 | plotPost( codaSamples[,"theta"] , main="theta" , xlab=bquote(theta) )
64 | saveGraph( file=paste0(fileNameRoot,"ThetaPost") , type="eps" )
65 | # Re-plot with different annotations:
66 | plotPost( codaSamples[,"theta"] , main="theta" , xlab=bquote(theta) ,
67 | cenTend="median" , compVal=0.5 , ROPE=c(0.45,0.55) , credMass=0.90 )
68 | saveGraph( file=paste0(fileNameRoot,"ThetaPost2") , type="eps" )
69 |
--------------------------------------------------------------------------------
/2e/Jags-Ybinom-Xnom1fac-Mlogistic-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | # Read the data
7 | myData = read.csv("BattingAverage.csv")
8 | contrasts = list(
9 | list( c("Pitcher") , c("Catcher") , compVal=0.0 , ROPE=NULL ) ,
10 | list( c("Catcher") , c("1st Base") , compVal=0.0 , ROPE=NULL )
11 | )
12 | fileNameRoot = "BattingAverage-logistic-"
13 | graphFileType = "eps"
14 | #-------------------------------------------------------------------------------
15 | # Load the relevant model into R's working memory:
16 | source("Jags-Ybinom-Xnom1fac-Mlogistic.R")
17 | # Generate the MCMC chain:
18 | #startTime = proc.time()
19 | mcmcCoda = genMCMC( datFrm=myData, yName="Hits", NName="AtBats", xName="PriPos",
20 | numSavedSteps=15000 , thinSteps=10 , saveName=fileNameRoot )
21 | #stopTime = proc.time()
22 | #elapsedTime = stopTime - startTime
23 | #show(elapsedTime)
24 | #-------------------------------------------------------------------------------
25 | # Display diagnostics of chain, for specified parameters:
26 | parameterNames = varnames(mcmcCoda) # get all parameter names for reference
27 | for ( parName in c("b0","b[1]","omega[1]","kappa") ) {
28 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
29 | saveName=fileNameRoot , saveType=graphFileType )
30 | }
31 | #-------------------------------------------------------------------------------
32 | # Get summary statistics of chain:
33 | summaryInfo = smryMCMC( mcmcCoda , contrasts=contrasts ,
34 | datFrm=myData, xName="PriPos",
35 | #yName="Hits", NName="AtBats",
36 | saveName=fileNameRoot )
37 | show(summaryInfo)
38 | # Display posterior information:
39 | plotMCMC( mcmcCoda , contrasts=contrasts ,
40 | datFrm=myData, xName="PriPos", yName="Hits", NName="AtBats",
41 | saveName=fileNameRoot , saveType=graphFileType )
42 | #-------------------------------------------------------------------------------
43 |
--------------------------------------------------------------------------------
/2e/Jags-Ybinom-XnomSsubjCcat-MbinomBetaOmegaKappa-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ybinom-XnomSsubjCcat-MbinomBetaOmegaKappa.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Read the data
8 | myData = read.csv("BattingAverage.csv")
9 | #-------------------------------------------------------------------------------
10 | # Load the relevant model into R's working memory:
11 | source("Jags-Ybinom-XnomSsubjCcat-MbinomBetaOmegaKappa.R")
12 | #-------------------------------------------------------------------------------
13 | # Optional: Specify filename root and graphical format for saving output.
14 | # Otherwise specify as NULL or leave saveName and saveType arguments
15 | # out of function calls.
16 | fileNameRoot = "BattingAverage-POST-"
17 | graphFileType = "eps"
18 | #-------------------------------------------------------------------------------
19 | # Generate the MCMC chain:
20 | startTime = proc.time()
21 | mcmcCoda = genMCMC( data=myData ,
22 | zName="Hits", NName="AtBats", sName="Player", cName="PriPos",
23 | numSavedSteps=11000 , saveName=fileNameRoot ,
24 | thinSteps=20 )
25 | stopTime = proc.time()
26 | elapsedTime = stopTime - startTime
27 | show(elapsedTime)
28 | #-------------------------------------------------------------------------------
29 | # Display diagnostics of chain, for specified parameters:
30 | parameterNames = varnames(mcmcCoda) # get all parameter names for reference
31 | for ( parName in c("omega[1]","omegaO","kappa[1]","kappaO","theta[1]") ) {
32 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
33 | saveName=fileNameRoot , saveType=graphFileType )
34 | }
35 | #-------------------------------------------------------------------------------
36 | # Get summary statistics of chain:
37 | summaryInfo = smryMCMC( mcmcCoda , compVal=NULL ,
38 | diffSVec=c(75,156, 159,844) ,
39 | diffCVec=c(1,2,3) ,
40 | compValDiff=0.0 , saveName=fileNameRoot )
41 | # Display posterior information:
42 | plotMCMC( mcmcCoda , data=myData ,
43 | zName="Hits", NName="AtBats", sName="Player", cName="PriPos",
44 | compVal=NULL ,
45 | diffCList=list( c("Pitcher","Catcher") ,
46 | c("Catcher","1st Base") ) ,
47 | diffSList=list( c("Kyle Blanks","Bruce Chen") ,
48 | c("Mike Leake","Wandy Rodriguez") ,
49 | c("Andrew McCutchen","Brett Jackson") ,
50 | c("ShinSoo Choo","Ichiro Suzuki") ) ,
51 | compValDiff=0.0, #ropeDiff = c(-0.05,0.05) ,
52 | saveName=fileNameRoot , saveType=graphFileType )
53 | #-------------------------------------------------------------------------------
54 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-XmetMulti-Mlogistic-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | # #.............................................................................
7 | # # Two predictors:
8 | # myData = read.csv( file="HtWtData110.csv" )
9 | # yName = "male" ; xName = c("weight","height")
10 | # fileNameRoot = "HtWtData110-"
11 | # numSavedSteps=15000 ; thinSteps=2
12 | # #.............................................................................
13 | # Only one predictor:
14 | myData = read.csv( file="HtWtData110.csv" )
15 | yName = "male" ; xName = c("weight")
16 | fileNameRoot = "HtWtData110-weightOnly-"
17 | numSavedSteps=15000 ; thinSteps=2
18 | # #.............................................................................
19 | # # Add some outliers:
20 | # outlierMat = matrix( c(
21 | # 190,74,0,
22 | # 230,73,0,
23 | # 120,59,1,
24 | # 150,58,1 ) , ncol=3 , byrow=TRUE ,
25 | # dimnames= list( NULL , c("weight","height","male") ) )
26 | # myData = rbind( myData , outlierMat )
27 | #.............................................................................
28 | graphFileType = "eps"
29 | #-------------------------------------------------------------------------------
30 | # Load the relevant model into R's working memory:
31 | source("Jags-Ydich-XmetMulti-Mlogistic.R")
32 | #-------------------------------------------------------------------------------
33 | # Generate the MCMC chain:
34 | #startTime = proc.time()
35 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
36 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
37 | saveName=fileNameRoot )
38 | #stopTime = proc.time()
39 | #duration = stopTime - startTime
40 | #show(duration)
41 | #-------------------------------------------------------------------------------
42 | # Display diagnostics of chain, for specified parameters:
43 | parameterNames = varnames(mcmcCoda) # get all parameter names
44 | for ( parName in parameterNames ) {
45 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
46 | saveName=fileNameRoot , saveType=graphFileType )
47 | }
48 | #-------------------------------------------------------------------------------
49 | # Get summary statistics of chain:
50 | summaryInfo = smryMCMC( mcmcCoda ,
51 | saveName=fileNameRoot )
52 | show(summaryInfo)
53 | # Display posterior information:
54 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
55 | pairsPlot=TRUE , showCurve=FALSE ,
56 | saveName=fileNameRoot , saveType=graphFileType )
57 | #-------------------------------------------------------------------------------
58 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-XmetMulti-MlogisticRobust-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | # #.............................................................................
7 | # # Two predictors:
8 | # myData = read.csv( file="HtWtData110.csv" )
9 | # yName = "male" ; xName = c("weight","height")
10 | # fileNameRoot = "HtWtData110-robust-"
11 | # numSavedSteps=15000 ; thinSteps=2
12 | # #.............................................................................
13 | # Only one predictor:
14 | myData = read.csv( file="HtWtData110.csv" )
15 | yName = "male" ; xName = c("weight")
16 | fileNameRoot = "HtWtData110-robust-weightOnly-"
17 | numSavedSteps=15000 ; thinSteps=2
18 | # #.............................................................................
19 | # # Add some outliers:
20 | # outlierMat = matrix( c(
21 | # 190,74,0,
22 | # 230,73,0,
23 | # 120,59,1,
24 | # 150,58,1 ) , ncol=3 , byrow=TRUE ,
25 | # dimnames= list( NULL , c("weight","height","male") ) )
26 | # myData = rbind( myData , outlierMat )
27 | #.............................................................................
28 | graphFileType = "eps"
29 | #-------------------------------------------------------------------------------
30 | # Load the relevant model into R's working memory:
31 | source("Jags-Ydich-XmetMulti-MlogisticRobust.R")
32 | #-------------------------------------------------------------------------------
33 | # Generate the MCMC chain:
34 | #startTime = proc.time()
35 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
36 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
37 | saveName=fileNameRoot )
38 | #stopTime = proc.time()
39 | #duration = stopTime - startTime
40 | #show(duration)
41 | #-------------------------------------------------------------------------------
42 | # Display diagnostics of chain, for specified parameters:
43 | parameterNames = varnames(mcmcCoda) # get all parameter names
44 | for ( parName in parameterNames ) {
45 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
46 | saveName=fileNameRoot , saveType=graphFileType )
47 | }
48 | #-------------------------------------------------------------------------------
49 | # Get summary statistics of chain:
50 | summaryInfo = smryMCMC( mcmcCoda ,
51 | saveName=fileNameRoot )
52 | show(summaryInfo)
53 | # Display posterior information:
54 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
55 | pairsPlot=TRUE , showCurve=FALSE ,
56 | saveName=fileNameRoot , saveType=graphFileType )
57 | #-------------------------------------------------------------------------------
58 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-Xnom1subj-MbernBeta-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ydich-Xnom1subj-MbernBeta.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data
8 | myData = read.csv("z15N50.csv")
9 | #-------------------------------------------------------------------------------
10 | # Load the functions genMCMC, smryMCMC, and plotMCMC:
11 | source("Jags-Ydich-Xnom1subj-MbernBeta.R")
12 | #-------------------------------------------------------------------------------
13 | # Optional: Specify filename root and graphical format for saving output.
14 | # Otherwise specify as NULL or leave saveName and saveType arguments
15 | # out of function calls.
16 | fileNameRoot = "Jags-Ydich-Xnom1subj-MbernBeta-"
17 | graphFileType = "eps"
18 | #-------------------------------------------------------------------------------
19 | # Generate the MCMC chain:
20 | mcmcCoda = genMCMC( data=myData , numSavedSteps=10000 , saveName=fileNameRoot )
21 | #-------------------------------------------------------------------------------
22 | # Display diagnostics of chain, for specified parameters:
23 | parameterNames = varnames(mcmcCoda) # get all parameter names
24 | for ( parName in parameterNames ) {
25 | diagMCMC( mcmcCoda , parName=parName ,
26 | saveName=fileNameRoot , saveType=graphFileType )
27 | }
28 | #-------------------------------------------------------------------------------
29 | # Get summary statistics of chain:
30 | summaryInfo = smryMCMC( mcmcCoda , compVal=0.5 , rope=c(0.45,0.55) ,
31 | saveName=fileNameRoot )
32 | # Display posterior information:
33 | plotMCMC( mcmcCoda , data=myData , # compVal=0.5 , rope=c(0.45,0.55) ,
34 | saveName=fileNameRoot , saveType=graphFileType )
35 | #-------------------------------------------------------------------------------
36 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-Xnom1subj-MbernBeta-Power.R:
--------------------------------------------------------------------------------
1 | # Jags-Ydich-Xnom1subj-MbernBeta-Power.R
2 | graphics.off() # This closes all of R's graphics windows.
3 | rm(list=ls()) # Careful! This clears all of R's memory!
4 | fileNameRoot = "Jags-Ydich-Xnom1subj-MbernBeta-Power-" # for future use
5 |
6 | # Load the functions genMCMC, smryMCMC, and plotMCMC:
7 | # (This also sources DBDA2E-utilities.R)
8 | source("Jags-Ydich-Xnom1subj-MbernBeta.R")
9 |
10 | # Define function that assesses goal achievement for a single set of data:
11 | goalAchievedForSample = function( data ) {
12 | # Generate the MCMC chain:
13 | mcmcCoda = genMCMC( data=data , numSavedSteps=10000 , saveName=NULL )
14 | # Check goal achievement. First, compute the HDI:
15 | thetaHDI = HDIofMCMC( as.matrix(mcmcCoda[,"theta"]) )
16 | # Define list for recording results:
17 | goalAchieved = list()
18 | # Goal: Exclude ROPE around null value:
19 | thetaROPE = c(0.48,0.52)
20 | goalAchieved = c( goalAchieved ,
21 | "ExcludeROPE"=( thetaHDI[1] > thetaROPE[2]
22 | | thetaHDI[2] < thetaROPE[1] ) )
23 | # Goal: HDI less than max width:
24 | thetaHDImaxWid = 0.2
25 | goalAchieved = c( goalAchieved ,
26 | "NarrowHDI"=( thetaHDI[2]-thetaHDI[1] < thetaHDImaxWid ) )
27 | # More goals can be inserted here if wanted...
28 | # Return list of goal results:
29 | return(goalAchieved)
30 | }
31 |
32 | # Specify mode and concentration of hypothetical parameter distribution:
33 | omega = 0.70
34 | kappa = 2000
35 | # Specify sample size for each simulated data set:
36 | sampleN = 74
37 | # Run a bunch of simulated experiments:
38 | nSimulatedDataSets = 1000 # An arbitrary large number.
39 | for ( simIdx in 1:nSimulatedDataSets ) {
40 | # Generate random value from hypothesized parameter distribution:
41 | genTheta = rbeta( 1 , omega*(kappa-2)+1 , (1-omega)*(kappa-2)+1 )
42 | # Generate random data based on parameter value:
43 | sampleZ = rbinom( 1 , size=sampleN , prob=genTheta )
44 | # Convert to vector of 0's and 1's for delivery to JAGS function:
45 | simulatedData = c(rep(1,sampleZ),rep(0,sampleN-sampleZ))
46 | # Do Bayesian analysis on simulated data:
47 | goalAchieved = goalAchievedForSample( simulatedData )
48 | # Tally the results:
49 | if (!exists("goalTally")) { # if goalTally does not exist, create it
50 | goalTally=matrix( nrow=0 , ncol=length(goalAchieved) )
51 | }
52 | goalTally = rbind( goalTally , goalAchieved )
53 | # save( goalTally ,
54 | # file="Jags-Ydich-Xnom1subj-MbernBeta-Power-goalTally.Rdata" )
55 | }
56 |
57 | # For each goal...
58 | for ( goalIdx in 1:NCOL(goalTally) ) {
59 | # Extract the goal name for subsequent display:
60 | goalName = colnames(goalTally)[goalIdx]
61 | # Compute number of successes:
62 | goalHits = sum(unlist(goalTally[,goalIdx]))
63 | # Compute number of attempts:
64 | goalAttempts = NROW(goalTally)
65 | # Compute proportion of successes:
66 | goalEst = goalHits/goalAttempts
67 | # Compute HDI around proportion:
68 | goalEstHDI = HDIofICDF( qbeta ,
69 | shape1=1+goalHits ,
70 | shape2=1+goalAttempts-goalHits )
71 | # Display the result:
72 | show( paste0( goalName,
73 | ": Est.Power=" , round(goalEst,3) ,
74 | "; Low Bound=" , round(goalEstHDI[1],3) ,
75 | "; High Bound=" , round(goalEstHDI[2],3) ) )
76 | }
77 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-XnomSsubj-MbernBeta-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ydich-XnomSsubj-Mbernbeta.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data
8 | myData = read.csv("z6N8z2N7.csv")
9 | # N.B.: The functions below expect the data to be a data frame,
10 | # with one component named y being a vector of integer 0,1 values,
11 | # and one component named s being a factor of subject identifiers.
12 | #-------------------------------------------------------------------------------
13 | # Load the relevant model into R's working memory:
14 | source("Jags-Ydich-XnomSsubj-MbernBeta.R")
15 | #-------------------------------------------------------------------------------
16 | # Optional: Specify filename root and graphical format for saving output.
17 | # Otherwise specify as NULL or leave saveName and saveType arguments
18 | # out of function calls.
19 | fileNameRoot = "Jags-Ydich-XnomSsubj-MbernBeta-"
20 | graphFileType = "eps"
21 | #-------------------------------------------------------------------------------
22 | # Generate the MCMC chain:
23 | mcmcCoda = genMCMC( data=myData , numSavedSteps=50000 , saveName=fileNameRoot )
24 | #-------------------------------------------------------------------------------
25 | # Display diagnostics of chain, for specified parameters:
26 | parameterNames = varnames(mcmcCoda) # get all parameter names
27 | for ( parName in parameterNames ) {
28 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
29 | saveName=fileNameRoot , saveType=graphFileType )
30 | }
31 | #-------------------------------------------------------------------------------
32 | # Get summary statistics of chain:
33 | summaryInfo = smryMCMC( mcmcCoda , compVal=NULL , #rope=c(0.45,0.55) ,
34 | compValDiff=0.0 , #ropeDiff = c(-0.05,0.05) ,
35 | saveName=fileNameRoot )
36 | # Display posterior information:
37 | plotMCMC( mcmcCoda , data=myData , compVal=NULL , #rope=c(0.45,0.55) ,
38 | compValDiff=0.0 , #ropeDiff = c(-0.05,0.05) ,
39 | saveName=fileNameRoot , saveType=graphFileType )
40 | #-------------------------------------------------------------------------------
41 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Read The data file:
8 | myData = read.csv("TherapeuticTouchData.csv")
9 | yName = "y" # column name for 0,1 values
10 | sName = "s" # column name for subject ID
11 | # Optional: Specify filename root and graphical format for saving output.
12 | # Otherwise specify as NULL or leave saveName and saveType arguments
13 | # out of function calls.
14 | fileNameRoot = "Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa-"
15 | graphFileType = "eps"
16 | #-------------------------------------------------------------------------------
17 | # # Read The data file:
18 | # myData = read.csv("StormTressoldiDiRisio2010data.csv")
19 | # yName = "Correct" # column name for 0,1 values
20 | # sName = "Study" # column name for "subject" ID
21 | # # Optional: Specify filename root and graphical format for saving output.
22 | # # Otherwise specify as NULL or leave saveName and saveType arguments
23 | # # out of function calls.
24 | # fileNameRoot = "StormTressoldiDiRisio2010-"
25 | # graphFileType = "eps"
26 | #-------------------------------------------------------------------------------
27 | # Load the relevant model into R's working memory:
28 | source("Jags-Ydich-XnomSsubj-MbernBetaOmegaKappa.R")
29 | #-------------------------------------------------------------------------------
30 | # Generate the MCMC chain:
31 | mcmcCoda = genMCMC( data=myData , sName=sName , yName=yName ,
32 | numSavedSteps=20000 , saveName=fileNameRoot , thinSteps=10 )
33 | #-------------------------------------------------------------------------------
34 | # Display diagnostics of chain, for specified parameters:
35 | parameterNames = varnames(mcmcCoda) # get all parameter names for reference
36 | for ( parName in parameterNames[c(1:3,length(parameterNames))] ) {
37 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
38 | saveName=fileNameRoot , saveType=graphFileType )
39 | }
40 | #-------------------------------------------------------------------------------
41 | # Get summary statistics of chain:
42 | summaryInfo = smryMCMC( mcmcCoda , compVal=0.5 ,
43 | diffIdVec=c(1,14,28), # Therapeutic touch
44 | # diffIdVec=c(38,60,2), # ESP Tressoldi et al.
45 | compValDiff=0.0 ,
46 | saveName=fileNameRoot )
47 | # Display posterior information:
48 | plotMCMC( mcmcCoda , data=myData , sName=sName , yName=yName ,
49 | compVal=0.5 , #rope=c(0.45,0.55) , # Therapeutic touch
50 | diffIdVec=c(1,14,28), # Therapeutic touch
51 | # compVal=0.25 , #rope=c(0.22,0.28) , # ESP Tressoldi et al.
52 | # diffIdVec=c(38,60,2), # ESP Tressoldi et al.
53 | compValDiff=0.0, #ropeDiff = c(-0.05,0.05) ,
54 | saveName=fileNameRoot , saveType=graphFileType )
55 | #-------------------------------------------------------------------------------
56 |
--------------------------------------------------------------------------------
/2e/Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data
8 | myData = read.csv("TherapeuticTouchData.csv")
9 | # N.B.: The functions below expect the data to be a data frame,
10 | # with one component named y being a vector of integer 0,1 values,
11 | # and one component named s being a factor of subject identifiers.
12 | #-------------------------------------------------------------------------------
13 | # Load the relevant model into R's working memory:
14 | source("Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa.R")
15 | #-------------------------------------------------------------------------------
16 | # Optional: Specify filename root and graphical format for saving output.
17 | # Otherwise specify as NULL or leave saveName and saveType arguments
18 | # out of function calls.
19 | fileNameRoot = "Jags-Ydich-XnomSsubj-MbinomBetaOmegaKappa-"
20 | graphFileType = "eps"
21 | #-------------------------------------------------------------------------------
22 | # Generate the MCMC chain:
23 | startTime = proc.time()
24 | mcmcCoda = genMCMC( data=myData , sName="s" , yName="y" ,
25 | numSavedSteps=20000 , saveName=fileNameRoot ,
26 | thinSteps=10 )
27 | stopTime = proc.time()
28 | show( stopTime-startTime )
29 | #-------------------------------------------------------------------------------
30 | # Display diagnostics of chain, for specified parameters:
31 | parameterNames = varnames(mcmcCoda) # get all parameter names for reference
32 | for ( parName in parameterNames[c(1:3,length(parameterNames))] ) {
33 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
34 | saveName=fileNameRoot , saveType=graphFileType )
35 | }
36 | #-------------------------------------------------------------------------------
37 | # Get summary statistics of chain:
38 | summaryInfo = smryMCMC( mcmcCoda , compVal=0.5 ,
39 | diffIdVec=c(1,14,28), compValDiff=0.0,
40 | saveName=fileNameRoot )
41 | # Display posterior information:
42 | plotMCMC( mcmcCoda , data=myData , sName="s" , yName="y" ,
43 | compVal=0.5 , #rope=c(0.45,0.55) ,
44 | diffIdVec=c(1,14,28), compValDiff=0.0, #ropeDiff = c(-0.05,0.05) ,
45 | saveName=fileNameRoot , saveType=graphFileType )
46 | #-------------------------------------------------------------------------------
47 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xmet-Mrobust-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xmet-Mrobust.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load data file and specity column names of x (predictor) and y (predicted):
8 | myData = read.csv( file="HtWtData30.csv" )
9 | xName = "height" ; yName = "weight"
10 | fileNameRoot = "HtWtData30-Jags-"
11 | #............................................................................
12 | # Load data file and specity column names of x (predictor) and y (predicted):
13 | # myData = read.csv( file="HtWtData300.csv" )
14 | # xName = "height" ; yName = "weight"
15 | # fileNameRoot = "HtWtData300-Jags-"
16 | #............................................................................
17 | graphFileType = "eps"
18 | #-------------------------------------------------------------------------------
19 | # Load the relevant model into R's working memory:
20 | source("Jags-Ymet-Xmet-Mrobust.R")
21 | #-------------------------------------------------------------------------------
22 | # Generate the MCMC chain:
23 | #startTime = proc.time()
24 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
25 | numSavedSteps=20000 , saveName=fileNameRoot )
26 | #stopTime = proc.time()
27 | #duration = stopTime - startTime
28 | #show(duration)
29 | #-------------------------------------------------------------------------------
30 | # Display diagnostics of chain, for specified parameters:
31 | parameterNames = varnames(mcmcCoda) # get all parameter names
32 | for ( parName in parameterNames ) {
33 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
34 | saveName=fileNameRoot , saveType=graphFileType )
35 | }
36 | #-------------------------------------------------------------------------------
37 | # Get summary statistics of chain:
38 | summaryInfo = smryMCMC( mcmcCoda ,
39 | compValBeta1=0.0 , ropeBeta1=c(-0.5,0.5) ,
40 | saveName=fileNameRoot )
41 | show(summaryInfo)
42 | # Display posterior information:
43 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
44 | compValBeta1=0.0 , ropeBeta1=c(-0.5,0.5) ,
45 | pairsPlot=TRUE , showCurve=FALSE ,
46 | saveName=fileNameRoot , saveType=graphFileType )
47 | #-------------------------------------------------------------------------------
48 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-XmetSsubj-MrobustHier-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-XmetSsubj-MrobustHier.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load data file and specity column names of x (predictor) and y (predicted):
8 |
9 | myData = read.csv( file="HierLinRegressData.csv" )
10 | xName = "X" ; yName = "Y" ; sName="Subj"
11 | fileNameRoot = "HierLinRegressData-Jags-"
12 |
13 | # myData = read.csv( file="IncomeFamszState.csv" )
14 | # xName = "Famsz" ; yName = "Income" ; sName="State"
15 | # fileNameRoot = "IncomeFamszState-Lin-Jags-"
16 |
17 | # myData = read.csv( file="BugsRatsData.csv" )
18 | # xName = "Day" ; yName = "Weight" ; sName="Subj"
19 | # fileNameRoot = "BugsRatsData-Jags-"
20 |
21 | graphFileType = "eps"
22 | #-------------------------------------------------------------------------------
23 | # Load the relevant model into R's working memory:
24 | source("Jags-Ymet-XmetSsubj-MrobustHier.R")
25 | #-------------------------------------------------------------------------------
26 | # Generate the MCMC chain:
27 | #startTime = proc.time()
28 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName , sName=sName ,
29 | numSavedSteps=20000 , thinSteps=15 , saveName=fileNameRoot )
30 | #stopTime = proc.time()
31 | #duration = stopTime - startTime
32 | #show(duration)
33 | # #-------------------------------------------------------------------------------
34 | # # Display diagnostics of chain, for specified parameters:
35 | parameterNames = varnames(mcmcCoda) # get all parameter names
36 | for ( parName in c("beta0mu","beta1mu","nu","sigma","beta0[1]","beta1[1]") ) {
37 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
38 | saveName=fileNameRoot , saveType=graphFileType )
39 | }
40 | #-------------------------------------------------------------------------------
41 | # Get summary statistics of chain:
42 | summaryInfo = smryMCMC( mcmcCoda , saveName=fileNameRoot )
43 | show(summaryInfo)
44 | # Display posterior information:
45 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName , sName=sName ,
46 | compValBeta1=0.0 , ropeBeta1=c(-0.5,0.5) ,
47 | pairsPlot=TRUE , showCurve=FALSE ,
48 | saveName=fileNameRoot , saveType=graphFileType )
49 | #-------------------------------------------------------------------------------
50 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-XmetSsubj-MrobustHierQuadWt-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-XmetSsubj-MrobustHierQuadWt.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load data file and specity column names of x (predictor) and y (predicted):
8 |
9 | myData = read.csv( file="IncomeFamszState3yr.csv" , comment.char="#")
10 | xName = "FamilySize" ; yName = "MedianIncome" ; sName="State" ; wName="SampErr"
11 | fileNameRoot = "IncomeFamszState3yr-Jags-"
12 |
13 | # myData = read.csv( file="HierLinRegressData.csv" )
14 | # xName = "X" ; yName = "Y" ; sName="Subj" ; wName=NULL
15 | # fileNameRoot = "HierLinRegressData-Quad-Jags-"
16 |
17 | # myData = read.csv( file="BugsRatsData.csv" )
18 | # xName = "Day" ; yName = "Weight" ; sName="Subj" ; wName=NULL
19 | # fileNameRoot = "BugsRatsData-Quad-Jags-"
20 |
21 | graphFileType = "eps"
22 | #-------------------------------------------------------------------------------
23 | # Load the relevant model into R's working memory:
24 | source("Jags-Ymet-XmetSsubj-MrobustHierQuadWt.R")
25 | #-------------------------------------------------------------------------------
26 | # Generate the MCMC chain:
27 | #startTime = proc.time()
28 | mcmcCoda = genMCMC( data=myData ,
29 | xName=xName , yName=yName , sName=sName , wName=wName ,
30 | numSavedSteps=20000 , thinSteps=15 , saveName=fileNameRoot )
31 | #stopTime = proc.time()
32 | #duration = stopTime - startTime
33 | #show(duration)
34 | # #-------------------------------------------------------------------------------
35 | # # Display diagnostics of chain, for specified parameters:
36 | parameterNames = varnames(mcmcCoda) # get all parameter names
37 | for ( parName in c("beta0mu","beta1mu","beta2mu","nu","sigma",
38 | "beta0[1]","beta1[1]","beta2[1]") ) {
39 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
40 | saveName=fileNameRoot , saveType=graphFileType )
41 | }
42 | #-------------------------------------------------------------------------------
43 | # Get summary statistics of chain:
44 | summaryInfo = smryMCMC( mcmcCoda , saveName=fileNameRoot )
45 | show(summaryInfo)
46 | # Display posterior information:
47 | plotMCMC( mcmcCoda , data=myData ,
48 | xName=xName , yName=yName , sName=sName , wName=wName ,
49 | pairsPlot=TRUE , showCurve=FALSE ,
50 | saveName=fileNameRoot , saveType=graphFileType )
51 | #-------------------------------------------------------------------------------
52 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xnom1fac-MrobustHet-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xnom1fac-MrobustHet.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 |
9 | # Comment out or uncomment one of the data sections below.
10 | # In RStudio, select section then press Cntrl-Shift-C
11 |
12 | # myDataFrame = read.csv( file="FruitflyDataReduced.csv" )
13 | # # Specify the column names in the data file relevant to the analysis:
14 | # yName="Longevity"
15 | # xName="CompanionNumber"
16 | # # Specify desired contrasts.
17 | # # Each main-effect contrast is a list of 2 vectors of level names,
18 | # # a comparison value (typically 0.0), and a ROPE (which could be NULL):
19 | # contrasts = list(
20 | # list( c("Pregnant1","Pregnant8") , c("None0") , compVal=0.0 , ROPE=c(-1,1) ) ,
21 | # list( c("Pregnant1","Pregnant8","None0") , c("Virgin1","Virgin8") ,
22 | # compVal=0.0 , ROPE=c(-1,1) ) ,
23 | # list( c("Pregnant1","Pregnant8","None0") , c("Virgin1") ,
24 | # compVal=0.0 , ROPE=c(-1,1) ) ,
25 | # list( c("Virgin1") , c("Virgin8") , compVal=0.0 , ROPE=c(-1,1) )
26 | # )
27 | # # Specify filename root and graphical format for saving output.
28 | # # Otherwise specify as NULL or leave saveName and saveType arguments
29 | # # out of function calls.
30 | # fileNameRoot = "FruitflyData-RobustHet-"
31 | # graphFileType = "eps"
32 |
33 |
34 | myDataFrame = read.csv( file="NonhomogVarData.csv" )
35 | yName="Y"
36 | xName="Group"
37 | contrasts = list(
38 | list( c("D") , c("A") , compVal=0.0 , ROPE=c(-1,1) ) ,
39 | list( c("C") , c("B") , compVal=0.0 , ROPE=c(-1,1) )
40 | )
41 | fileNameRoot = "NonhomogVarData-RobustHet-"
42 | graphFileType = "eps"
43 |
44 | #-------------------------------------------------------------------------------
45 | # Load the relevant model into R's working memory:
46 | source("Jags-Ymet-Xnom1fac-MrobustHet.R")
47 | #-------------------------------------------------------------------------------
48 | # Generate the MCMC chain:
49 | mcmcCoda = genMCMC( datFrm=myDataFrame , yName=yName , xName=xName ,
50 | numSavedSteps=11000 , thinSteps=20 , saveName=fileNameRoot )
51 | #-------------------------------------------------------------------------------
52 | # Display diagnostics of chain, for specified parameters:
53 | parameterNames = varnames(mcmcCoda)
54 | show( parameterNames ) # show all parameter names, for reference
55 | for ( parName in c("aSigma","b0","b[1]","ySigma[1]", "nu","ySigmaMode","ySigmaSD") ) {
56 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
57 | saveName=fileNameRoot , saveType=graphFileType )
58 | }
59 | #-------------------------------------------------------------------------------
60 | # Get summary statistics of chain:
61 | summaryInfo = smryMCMC( mcmcCoda ,
62 | datFrm=myDataFrame , xName=xName ,
63 | contrasts=contrasts ,
64 | saveName=fileNameRoot )
65 | show(summaryInfo)
66 | # Display posterior information:
67 | plotMCMC( mcmcCoda ,
68 | datFrm=myDataFrame , yName=yName , xName=xName ,
69 | contrasts=contrasts ,
70 | saveName=fileNameRoot , saveType=graphFileType )
71 | #-------------------------------------------------------------------------------
72 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xnom1grp-Mnormal-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xnom1grp-Mnormal.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 | myDataFrame = read.csv( file="TwoGroupIQ.csv" )
9 | # For purposes of this one-group example, use data from Smart Drug group:
10 | myData = myDataFrame$Score[myDataFrame$Group=="Smart Drug"]
11 | #-------------------------------------------------------------------------------
12 | # Optional: Specify filename root and graphical format for saving output.
13 | # Otherwise specify as NULL or leave saveName and saveType arguments
14 | # out of function calls.
15 | fileNameRoot = "OneGroupIQnormal-"
16 | graphFileType = "eps"
17 | #-------------------------------------------------------------------------------
18 | # Load the relevant model into R's working memory:
19 | source("Jags-Ymet-Xnom1grp-Mnormal.R")
20 | #-------------------------------------------------------------------------------
21 | # Generate the MCMC chain:
22 | mcmcCoda = genMCMC( data=myData , numSavedSteps=20000 , saveName=fileNameRoot )
23 | #-------------------------------------------------------------------------------
24 | # Display diagnostics of chain, for specified parameters:
25 | parameterNames = varnames(mcmcCoda) # get all parameter names
26 | for ( parName in parameterNames ) {
27 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
28 | saveName=fileNameRoot , saveType=graphFileType )
29 | }
30 | #-------------------------------------------------------------------------------
31 | # Get summary statistics of chain:
32 | summaryInfo = smryMCMC( mcmcCoda ,
33 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
34 | compValSigma=15.0 , ropeSigma=c(14,16) ,
35 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
36 | saveName=fileNameRoot )
37 | show(summaryInfo)
38 | # Display posterior information:
39 | plotMCMC( mcmcCoda , data=myData ,
40 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
41 | compValSigma=15.0 , ropeSigma=c(14,16) ,
42 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
43 | pairsPlot=TRUE , showCurve=FALSE ,
44 | saveName=fileNameRoot , saveType=graphFileType )
45 | #-------------------------------------------------------------------------------
46 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xnom1grp-Mrobust-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xnom1grp-Mrobust.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 | myDataFrame = read.csv( file="TwoGroupIQ.csv" )
9 | # For purposes of this one-group example, use data from Smart Drug group:
10 | myData = myDataFrame$Score[myDataFrame$Group=="Smart Drug"]
11 | #-------------------------------------------------------------------------------
12 | # Optional: Specify filename root and graphical format for saving output.
13 | # Otherwise specify as NULL or leave saveName and saveType arguments
14 | # out of function calls.
15 | fileNameRoot = "OneGroupIQrobust-Jags-"
16 | graphFileType = "eps"
17 | #-------------------------------------------------------------------------------
18 | # Load the relevant model into R's working memory:
19 | source("Jags-Ymet-Xnom1grp-Mrobust.R")
20 | #-------------------------------------------------------------------------------
21 | # Generate the MCMC chain:
22 | mcmcCoda = genMCMC( data=myData , numSavedSteps=20000 , saveName=fileNameRoot )
23 | #-------------------------------------------------------------------------------
24 | # Display diagnostics of chain, for specified parameters:
25 | parameterNames = varnames(mcmcCoda) # get all parameter names
26 | for ( parName in parameterNames ) {
27 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
28 | saveName=fileNameRoot , saveType=graphFileType )
29 | }
30 | #-------------------------------------------------------------------------------
31 | # Get summary statistics of chain:
32 | summaryInfo = smryMCMC( mcmcCoda ,
33 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
34 | compValSigma=15.0 , ropeSigma=c(14,16) ,
35 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
36 | saveName=fileNameRoot )
37 | show(summaryInfo)
38 | # Display posterior information:
39 | plotMCMC( mcmcCoda , data=myData ,
40 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
41 | compValSigma=15.0 , ropeSigma=c(14,16) ,
42 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
43 | pairsPlot=TRUE , showCurve=FALSE ,
44 | saveName=fileNameRoot , saveType=graphFileType )
45 | #-------------------------------------------------------------------------------
46 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xnom1met1-MnormalHom-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xnom1met1-MnormalHom.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 |
9 | myDataFrame = read.csv( file="FruitflyDataReduced.csv" )
10 | # Specify the column names in the data file relevant to the analysis:
11 | yName="Longevity"
12 | xNomName="CompanionNumber"
13 | xMetName="Thorax" # the covariate
14 | # Specify desired contrasts.
15 | # Each main-effect contrast is a list of 2 vectors of level names,
16 | # a comparison value (typically 0.0), and a ROPE (which could be NULL):
17 | contrasts = list(
18 | list( c("Pregnant1","Pregnant8") , c("None0") , compVal=0.0 , ROPE=c(-1.5,1.5) ) ,
19 | list( c("Pregnant1","Pregnant8","None0") , c("Virgin1","Virgin8") ,
20 | compVal=0.0 , ROPE=c(-1.5,1.5) ) ,
21 | list( c("Pregnant1","Pregnant8","None0") , c("Virgin1") ,
22 | compVal=0.0 , ROPE=c(-1.5,1.5) ) ,
23 | list( c("Virgin1") , c("Virgin8") , compVal=0.0 , ROPE=c(-1.5,1.5) )
24 | )
25 | # Specify filename root and graphical format for saving output.
26 | # Otherwise specify as NULL or leave saveName and saveType arguments
27 | # out of function calls.
28 | fileNameRoot = "FruitflyData-ThoraxCovariate-"
29 | graphFileType = "eps"
30 |
31 | #-------------------------------------------------------------------------------
32 | # Load the relevant model into R's working memory:
33 | source("Jags-Ymet-Xnom1met1-MnormalHom.R")
34 | #-------------------------------------------------------------------------------
35 | # Generate the MCMC chain:
36 | mcmcCoda = genMCMC( datFrm=myDataFrame ,
37 | yName=yName , xNomName=xNomName , xMetName=xMetName ,
38 | numSavedSteps=11000 , thinSteps=10 , saveName=fileNameRoot )
39 | #-------------------------------------------------------------------------------
40 | # Display diagnostics of chain, for specified parameters:
41 | parameterNames = varnames(mcmcCoda)
42 | show( parameterNames ) # show all parameter names, for reference
43 | for ( parName in parameterNames ) {
44 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
45 | saveName=fileNameRoot , saveType=graphFileType )
46 | }
47 | #-------------------------------------------------------------------------------
48 | # Get summary statistics of chain:
49 | summaryInfo = smryMCMC( mcmcCoda , datFrm=myDataFrame , xNomName=xNomName ,
50 | xMetName=xMetName , contrasts=contrasts ,
51 | saveName=fileNameRoot )
52 | show(summaryInfo)
53 | # Display posterior information:
54 | plotMCMC( mcmcCoda , datFrm=myDataFrame , yName=yName , xNomName=xNomName ,
55 | xMetName=xMetName , contrasts=contrasts ,
56 | saveName=fileNameRoot , saveType=graphFileType )
57 | #-------------------------------------------------------------------------------
58 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-Xnom2grp-MrobustHet-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-Xnom2grp-MrobustHet.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 |
9 | myDataFrame = read.csv( file="TwoGroupIQ.csv" )
10 | yName="Score"
11 | xName="Group"
12 | fileNameRoot = "TwoGroupIQrobustHet-"
13 | RopeMuDiff=c(-0.5,0.5) ; RopeSdDiff=c(-0.5,0.5) ; RopeEff=c(-0.1,0.1)
14 |
15 | # myDataFrame = read.csv( file="ShohatOphirKAMH2012dataReduced.csv" )
16 | # xName="Group"
17 | # yName="PreferenceIndex"
18 | # fileNameRoot="ShohatOphirKAMH2012data-PI-"
19 | # RopeMuDiff=c(-0.1,0.1) ; RopeSdDiff=c(-0.1,0.1) ; RopeEff=c(-0.1,0.1)
20 |
21 | # myDataFrame = read.csv( file="ShohatOphirKAMH2012dataReduced.csv" )
22 | # xName="Group"
23 | # yName="GrandTotal"
24 | # fileNameRoot="ShohatOphirKAMH2012data-GT-"
25 | # RopeMuDiff=c(-0.1,0.1) ; RopeSdDiff=c(-0.1,0.1) ; RopeEff=c(-0.1,0.1)
26 |
27 | # myDataFrame = read.csv( file="RatLives.csv" )
28 | # xName="Group"
29 | # yName="DaysLive"
30 | # fileNameRoot = "RatLives-"
31 | # RopeMuDiff=c(-10,10) ; RopeSdDiff=c(-10,10) ; RopeEff=c(-0.1,0.1)
32 |
33 | # myDataFrame = read.csv( file="RatLives.csv" )
34 | # xName="Group"
35 | # myDataFrame = cbind( myDataFrame , DaysLiveSq = myDataFrame$DaysLive^2 )
36 | # yName="DaysLiveSq"
37 | # fileNameRoot = "RatLives-DaySq-"
38 | # RopeMuDiff=c(-100,100) ; RopeSdDiff=c(-100,100) ; RopeEff=c(-0.1,0.1)
39 |
40 | graphFileType = "eps"
41 | #-------------------------------------------------------------------------------
42 | # Load the relevant model into R's working memory:
43 | source("Jags-Ymet-Xnom2grp-MrobustHet.R")
44 | #-------------------------------------------------------------------------------
45 | # Generate the MCMC chain:
46 | mcmcCoda = genMCMC( datFrm=myDataFrame , yName=yName , xName=xName ,
47 | numSavedSteps=50000 , saveName=fileNameRoot )
48 | #-------------------------------------------------------------------------------
49 | # Display diagnostics of chain, for specified parameters:
50 | parameterNames = varnames(mcmcCoda) # get all parameter names
51 | for ( parName in parameterNames ) {
52 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
53 | saveName=fileNameRoot , saveType=graphFileType )
54 | }
55 | #-------------------------------------------------------------------------------
56 | # Get summary statistics of chain:
57 | summaryInfo = smryMCMC( mcmcCoda , RopeMuDiff=RopeMuDiff ,
58 | RopeSdDiff=RopeSdDiff , RopeEff=RopeEff ,
59 | saveName=fileNameRoot )
60 | show(summaryInfo)
61 | # Display posterior information:
62 | plotMCMC( mcmcCoda , datFrm=myDataFrame , yName=yName , xName=xName ,
63 | RopeMuDiff=RopeMuDiff , RopeSdDiff=RopeSdDiff , RopeEff=RopeEff ,
64 | pairsPlot=TRUE , saveName=fileNameRoot , saveType=graphFileType )
65 | #-------------------------------------------------------------------------------
66 |
--------------------------------------------------------------------------------
/2e/Jags-Ymet-XnomSplitPlot-MnormalHom-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-XnomSplitPlot-MnormalHom.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | #Load The data file
8 |
9 | fileNameRoot = "SplitPlotAgriData-"
10 | graphFileType = "eps"
11 | myDataFrame = read.csv( "SplitPlotAgriData.csv" )
12 | # Specify the column names in the data file relevant to the analysis:
13 | yName="Yield"
14 | xBetweenName="Till"
15 | xWithinName="Fert"
16 | xSubjectName="Field"
17 | xBetweenContrasts = list(
18 | list( c("Moldbrd") , c("Ridge") , compVal=0.0 , ROPE=c(-5,5) ) ,
19 | list( c("Moldbrd","Ridge") , c("Chisel") , compVal=0.0 , ROPE=c(-5,5) )
20 | )
21 | xWithinContrasts = list(
22 | list( c("Deep","Surface") , c("Broad") , compVal=0.0 , ROPE=c(-5,5) )
23 | )
24 | xBetweenWithinContrasts = list(
25 | list( list( c("Chisel","Moldbrd") , c("Ridge") ) ,
26 | list( c("Broad") , c("Deep","Surface") ) ,
27 | compVal=0.0 , ROPE=c(-5,5) )
28 | )
29 |
30 | #-------------------------------------------------------------------------------
31 | # Load the relevant model into R's working memory:
32 | source("Jags-Ymet-XnomSplitPlot-MnormalHom.R")
33 | #-------------------------------------------------------------------------------
34 | # Generate the MCMC chain:
35 | mcmcCoda = genMCMC( datFrm=myDataFrame ,
36 | yName=yName , xBetweenName=xBetweenName ,
37 | xWithinName=xWithinName , xSubjectName=xSubjectName ,
38 | numSavedSteps=12000 , thinSteps=20 , saveName=fileNameRoot )
39 | #-------------------------------------------------------------------------------
40 | # Display diagnostics of chain, for specified parameters:
41 | parameterNames = varnames(mcmcCoda)
42 | show( parameterNames ) # show all parameter names, for reference
43 | for ( parName in c("mSxW[1,1]","b0","bB[1]","bW[1]","bS[1]","bBxW[1,1]",
44 | "sigma","sigmaB","sigmaW","sigmaS","sigmaBxW") ) {
45 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
46 | saveName=fileNameRoot , saveType=graphFileType )
47 | }
48 | #-------------------------------------------------------------------------------
49 | # Get summary statistics of chain:
50 | summaryInfo = smryMCMC( mcmcCoda ,
51 | datFrm=myDataFrame , xBetweenName=xBetweenName ,
52 | xWithinName=xWithinName , xSubjectName=xSubjectName ,
53 | xBetweenContrasts=xBetweenContrasts ,
54 | xWithinContrasts=xWithinContrasts ,
55 | xBetweenWithinContrasts=xBetweenWithinContrasts ,
56 | saveName=fileNameRoot )
57 | show(summaryInfo)
58 | # Display posterior information:
59 | plotMCMC( mcmcCoda ,
60 | datFrm=myDataFrame , yName=yName , xBetweenName=xBetweenName ,
61 | xWithinName=xWithinName , xSubjectName=xSubjectName ,
62 | xBetweenContrasts=xBetweenContrasts ,
63 | xWithinContrasts=xWithinContrasts ,
64 | xBetweenWithinContrasts=xBetweenWithinContrasts ,
65 | saveName=fileNameRoot , saveType=graphFileType )
66 | #-------------------------------------------------------------------------------
67 |
--------------------------------------------------------------------------------
/2e/Jags-Ynom-XmetMulti-McondLogistic1-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | #.............................................................................
7 | myData = read.csv( file="CondLogistRegData1.csv" )
8 | yName = "Y" ; xName = c("X1","X2")
9 | fileNameRoot = "CondLogistRegData1-Model1-"
10 | numSavedSteps=5000 ; thinSteps=5
11 | #.............................................................................
12 | # myData = read.csv( file="CondLogistRegData2.csv" )
13 | # yName = "Y" ; xName = c("X1","X2")
14 | # fileNameRoot = "CondLogistRegData2-Model1-"
15 | # numSavedSteps=5000 ; thinSteps=5
16 | #.............................................................................
17 | # myData = read.csv( file="SoftmaxRegData1.csv" )
18 | # yName = "Y" ; xName = c("X1","X2")
19 | # fileNameRoot = "SoftmaxRegData1-Model1-"
20 | # numSavedSteps=5000 ; thinSteps=5
21 | #.............................................................................
22 | # myData = read.csv( file="SoftmaxRegData2.csv" )
23 | # yName = "Y" ; xName = c("X1","X2")
24 | # fileNameRoot = "SoftmaxRegData2-Model1-"
25 | # numSavedSteps=5000 ; thinSteps=5
26 | #.............................................................................
27 | graphFileType = "eps"
28 | #-------------------------------------------------------------------------------
29 | # Load the relevant model into R's working memory:
30 | source("Jags-Ynom-XmetMulti-McondLogistic1.R")
31 | #-------------------------------------------------------------------------------
32 | # Generate the MCMC chain:
33 | #startTime = proc.time()
34 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
35 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
36 | saveName=fileNameRoot )
37 | #stopTime = proc.time()
38 | #duration = stopTime - startTime
39 | #show(duration)
40 | #-------------------------------------------------------------------------------
41 | # Display diagnostics of chain, for specified parameters:
42 | parameterNames = varnames(mcmcCoda) # get all parameter names
43 | for ( parName in grep( "^beta" , parameterNames , value=TRUE ) ) {
44 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
45 | saveName=fileNameRoot , saveType=graphFileType )
46 | }
47 | #-------------------------------------------------------------------------------
48 | # Get summary statistics of chain:
49 | summaryInfo = smryMCMC( mcmcCoda ,
50 | saveName=fileNameRoot )
51 | show(summaryInfo)
52 | # Display posterior information:
53 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
54 | pairsPlot=TRUE , showCurve=FALSE ,
55 | saveName=fileNameRoot , saveType=graphFileType )
56 | #-------------------------------------------------------------------------------
57 |
--------------------------------------------------------------------------------
/2e/Jags-Ynom-XmetMulti-McondLogistic2-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | #.............................................................................
7 | # myData = read.csv( file="CondLogistRegData1.csv" )
8 | # yName = "Y" ; xName = c("X1","X2")
9 | # fileNameRoot = "CondLogistRegData1-Model2-"
10 | # numSavedSteps=5000 ; thinSteps=5
11 | #.............................................................................
12 | myData = read.csv( file="CondLogistRegData2.csv" )
13 | yName = "Y" ; xName = c("X1","X2")
14 | fileNameRoot = "CondLogistRegData2-Model2-"
15 | numSavedSteps=5000 ; thinSteps=5
16 | #.............................................................................
17 | # myData = read.csv( file="SoftmaxRegData1.csv" )
18 | # yName = "Y" ; xName = c("X1","X2")
19 | # fileNameRoot = "SoftmaxRegData1-Model2-"
20 | # numSavedSteps=5000 ; thinSteps=5
21 | #.............................................................................
22 | # myData = read.csv( file="SoftmaxRegData2.csv" )
23 | # yName = "Y" ; xName = c("X1","X2")
24 | # fileNameRoot = "SoftmaxRegData2-Model2-"
25 | # numSavedSteps=5000 ; thinSteps=5
26 | #.............................................................................
27 | graphFileType = "eps"
28 | #-------------------------------------------------------------------------------
29 | # Load the relevant model into R's working memory:
30 | source("Jags-Ynom-XmetMulti-McondLogistic2.R")
31 | #-------------------------------------------------------------------------------
32 | # Generate the MCMC chain:
33 | #startTime = proc.time()
34 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
35 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
36 | saveName=fileNameRoot )
37 | #stopTime = proc.time()
38 | #duration = stopTime - startTime
39 | #show(duration)
40 | #-------------------------------------------------------------------------------
41 | # Display diagnostics of chain, for specified parameters:
42 | parameterNames = varnames(mcmcCoda) # get all parameter names
43 | for ( parName in grep( "^beta" , parameterNames , value=TRUE ) ) {
44 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
45 | saveName=fileNameRoot , saveType=graphFileType )
46 | }
47 | #-------------------------------------------------------------------------------
48 | # Get summary statistics of chain:
49 | summaryInfo = smryMCMC( mcmcCoda ,
50 | saveName=fileNameRoot )
51 | show(summaryInfo)
52 | # Display posterior information:
53 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
54 | pairsPlot=TRUE , showCurve=FALSE ,
55 | saveName=fileNameRoot , saveType=graphFileType )
56 | #-------------------------------------------------------------------------------
57 |
--------------------------------------------------------------------------------
/2e/Jags-Ynom-XmetMulti-Msoftmax-Example.R:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Optional generic preliminaries:
3 | graphics.off() # This closes all of R's graphics windows.
4 | rm(list=ls()) # Careful! This clears all of R's memory!
5 | #-------------------------------------------------------------------------------
6 | #.............................................................................
7 | myData = read.csv( file="SoftmaxRegData1.csv" )
8 | yName = "Y" ; xName = c("X1","X2")
9 | fileNameRoot = "SoftmaxRegData1-"
10 | numSavedSteps=5000 ; thinSteps=5
11 | #.............................................................................
12 | # myData = read.csv( file="SoftmaxRegData2.csv" )
13 | # yName = "Y" ; xName = c("X1","X2")
14 | # fileNameRoot = "SoftmaxRegData2-"
15 | # numSavedSteps=5000 ; thinSteps=5
16 | #.............................................................................
17 | # myData = read.csv( file="CondLogistRegData1.csv" )
18 | # yName = "Y" ; xName = c("X1","X2")
19 | # fileNameRoot = "CondLogistRegData1-Softmax-"
20 | # numSavedSteps=5000 ; thinSteps=5
21 | #.............................................................................
22 | # myData = read.csv( file="CondLogistRegData2.csv" )
23 | # yName = "Y" ; xName = c("X1","X2")
24 | # fileNameRoot = "CondLogistRegData2-Softmax-"
25 | # numSavedSteps=5000 ; thinSteps=5
26 | #.............................................................................
27 | graphFileType = "eps"
28 | #-------------------------------------------------------------------------------
29 | # Load the relevant model into R's working memory:
30 | source("Jags-Ynom-XmetMulti-Msoftmax.R")
31 | #-------------------------------------------------------------------------------
32 | # Generate the MCMC chain:
33 | #startTime = proc.time()
34 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
35 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
36 | saveName=fileNameRoot )
37 | #stopTime = proc.time()
38 | #duration = stopTime - startTime
39 | #show(duration)
40 | #-------------------------------------------------------------------------------
41 | # Display diagnostics of chain, for specified parameters:
42 | parameterNames = varnames(mcmcCoda) # get all parameter names
43 | for ( parName in grep( "^beta" , parameterNames , value=TRUE ) ) {
44 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
45 | saveName=fileNameRoot , saveType=graphFileType )
46 | }
47 | #-------------------------------------------------------------------------------
48 | # Get summary statistics of chain:
49 | summaryInfo = smryMCMC( mcmcCoda ,
50 | saveName=fileNameRoot )
51 | show(summaryInfo)
52 | # Display posterior information:
53 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
54 | pairsPlot=TRUE , showCurve=FALSE ,
55 | saveName=fileNameRoot , saveType=graphFileType )
56 | #-------------------------------------------------------------------------------
57 |
--------------------------------------------------------------------------------
/2e/Jags-Yord-XmetMulti-Mnormal-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Ymet-XmetMulti-Mrobust.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | # UNCOMMENT ONE OF THE FOLLOWING SECTIONS (In RStudio, select and ctrl-shift-C)
7 | #.............................................................................
8 | myData = read.csv( file="OrdinalProbitData-LinReg-2.csv" )
9 | yName = "Y" ; xName = c("X")
10 | fileNameRoot = "OrdinalProbitData-LinReg-2-"
11 | numSavedSteps=5000 ; thinSteps=2 # increase for higher ESS
12 | lmInfo <- lm( myData[,yName] ~ myData[,xName[1]] , data=myData )
13 | #.............................................................................
14 | # myData = read.csv( file="Movies.csv" ) # Real data
15 | # yName = "Rating" ; xName = c("Year","Length")
16 | # # convert 1/2 scale ratings to integers:
17 | # myData$Rating = as.numeric(as.factor(myData$Rating))
18 | # fileNameRoot = "Movies-"
19 | # numSavedSteps=5000 ; thinSteps=1 # increase for higher ESS
20 | # lmInfo <- lm( myData[,yName] ~ myData[,xName[1]] + myData[,xName[2]] , data=myData )
21 | #.............................................................................
22 | # myData = read.csv( file="OrdinalProbitData-Movies.csv" ) # Fictitious data
23 | # yName = "Rating" ; xName = c("Year","Length")
24 | # fileNameRoot = "OrdinalProbitData-Movies-"
25 | # numSavedSteps=5000 ; thinSteps=1 # increase for higher ESS
26 | # lmInfo <- lm( myData[,yName] ~ myData[,xName[1]] + myData[,xName[2]] , data=myData )
27 | #.............................................................................
28 | # myData = read.csv("HappinessAssetsDebt.csv")
29 | # yName = "Happiness"
30 | # xName = c("Assets","Debt")[1]
31 | # # # get random subset of reduced size:
32 | # # subRows = sample( 1:nrow(myData) )
33 | # # subRows = subRows[1:500]
34 | # # myData = myData[subRows,]
35 | # fileNameRoot = paste0("HappinessAssetsDebt-",paste(xName,collapse="-"),"-")
36 | # numSavedSteps=12000 ; thinSteps=5
37 | #.............................................................................
38 | graphFileType = "eps"
39 | #-------------------------------------------------------------------------------
40 | # Load the relevant model into R's working memory:
41 | source("Jags-Yord-XmetMulti-Mnormal.R")
42 | #-------------------------------------------------------------------------------
43 | # Generate the MCMC chain:
44 | #startTime = proc.time()
45 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
46 | numSavedSteps=numSavedSteps , thinSteps=thinSteps ,
47 | saveName=fileNameRoot )
48 | #stopTime = proc.time()
49 | #duration = stopTime - startTime
50 | #show(duration)
51 | #-------------------------------------------------------------------------------
52 | # Display diagnostics of chain, for specified parameters:
53 | parameterNames = varnames(mcmcCoda) # get all parameter names
54 | for ( parName in parameterNames ) {
55 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
56 | saveName=fileNameRoot , saveType=graphFileType )
57 | }
58 | #-------------------------------------------------------------------------------
59 | # Get summary statistics of chain:
60 | summaryInfo = smryMCMC( mcmcCoda ,
61 | saveName=fileNameRoot )
62 | show(summaryInfo)
63 | # Display posterior information:
64 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
65 | pairsPlot=TRUE , showCurve=FALSE ,
66 | saveName=fileNameRoot , saveType=graphFileType )
67 | #-------------------------------------------------------------------------------
68 | # NHST analysis:
69 | show( summary( lmInfo ) )
70 |
71 |
--------------------------------------------------------------------------------
/2e/Jags-Yord-Xnom1grp-Mnormal-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Yord-Xnom1grp-Mnormal.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | myDataFrame = read.csv( file="OrdinalProbitData-1grp-1.csv" )
8 | yName="Y"
9 | compVal=2.0
10 | fileNameRoot="OrdinalProbitData-1grp-1-"
11 | #.....................................................................
12 | # myDataFrame = read.csv( file="OrdinalProbitData-1grp-2.csv" )
13 | # yName="Y"
14 | # compVal=4.0
15 | # fileNameRoot="OrdinalProbitData-1grp-2-"
16 | #-------------------------------------------------------------------------------
17 | # Load the relevant model into R's working memory:
18 | source("Jags-Yord-Xnom1grp-Mnormal.R")
19 | #-------------------------------------------------------------------------------
20 | # Optional: Specify filename root and graphical format for saving output.
21 | # Otherwise specify as NULL or leave saveName and saveType arguments
22 | # out of function calls.
23 | graphFileType = "eps"
24 | #-------------------------------------------------------------------------------
25 | # Generate the MCMC chain:
26 | mcmcCoda = genMCMC( datFrm=myDataFrame , yName=yName ,
27 | numSavedSteps=15000 , thinSteps=10 ,
28 | # numSavedSteps=5000 , thinSteps=2 ,
29 | saveName=fileNameRoot )
30 | #-------------------------------------------------------------------------------
31 | # Display diagnostics of chain, for specified parameters:
32 | # Get all parameter names:
33 | parameterNames = varnames(mcmcCoda)
34 | for ( parName in parameterNames ) {
35 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
36 | saveName=fileNameRoot , saveType=graphFileType )
37 | }
38 | #-------------------------------------------------------------------------------
39 | # Get summary statistics of chain:
40 | summaryInfo = smryMCMC( mcmcCoda , compVal=compVal ,
41 | saveName=fileNameRoot )
42 | show(summaryInfo)
43 | # Display posterior information:
44 | plotMCMC( mcmcCoda , datFrm=myDataFrame , yName=yName ,
45 | compVal=compVal ,
46 | pairsPlot=TRUE , saveName=fileNameRoot , saveType=graphFileType )
47 | #-------------------------------------------------------------------------------
48 |
49 | # NHST tests:
50 | # t test of mean:
51 | tInfo = t.test(myDataFrame[,yName],mu=compVal)
52 | show(tInfo)
53 | tEffSz = (mean(myDataFrame[,yName])-compVal)/sd(myDataFrame[,yName])
54 | show(tEffSz)
55 | show(sd(myDataFrame[,yName]))
56 |
57 |
--------------------------------------------------------------------------------
/2e/Jags-Yord-Xnom2grp-MnormalHet-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Jags-Yord-Xnom2grp-MrobustHet.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 | #....................................................................
9 | myDataFrame = read.csv( file="OrdinalProbitData1.csv" )
10 | yName="Y"
11 | xName="X"
12 | fileNameRoot="OrdinalProbitData1-"
13 | #-------------------------------------------------------------------------------
14 | # Load the relevant model into R's working memory:
15 | source("Jags-Yord-Xnom2grp-MnormalHet.R")
16 | #-------------------------------------------------------------------------------
17 | # Optional: Specify filename root and graphical format for saving output.
18 | # Otherwise specify as NULL or leave saveName and saveType arguments
19 | # out of function calls.
20 | graphFileType = "eps"
21 | #-------------------------------------------------------------------------------
22 | # Generate the MCMC chain:
23 | mcmcCoda = genMCMC( datFrm=myDataFrame , yName=yName , xName=xName ,
24 | numSavedSteps=12000 , thinSteps=3 ,
25 | # numSavedSteps=5000 , thinSteps=1 ,
26 | saveName=fileNameRoot )
27 | #-------------------------------------------------------------------------------
28 | # Display diagnostics of chain, for specified parameters:
29 | # Get all parameter names:
30 | parameterNames = varnames(mcmcCoda)
31 | # for ( parName in parameterNames ) {
32 | # diagMCMC( codaObject=mcmcCoda , parName=parName ,
33 | # saveName=fileNameRoot , saveType=graphFileType )
34 | # }
35 | #-------------------------------------------------------------------------------
36 | # Get summary statistics of chain:
37 | summaryInfo = smryMCMC( mcmcCoda , RopeMuDiff=c(-0.2,0.2) ,
38 | RopeSdDiff=c(-0.2,0.2) , RopeEff=c(-0.1,0.1) ,
39 | saveName=fileNameRoot )
40 | show(summaryInfo)
41 | # Display posterior information:
42 | plotMCMC( mcmcCoda , datFrm=myDataFrame , yName=yName , xName=xName ,
43 | RopeMuDiff=c(-0.2,0.2) , RopeSdDiff=c(-0.2,0.2), RopeEff=c(-0.1,0.1) ,
44 | pairsPlot=TRUE , saveName=fileNameRoot , saveType=graphFileType )
45 | #-------------------------------------------------------------------------------
46 |
47 | # NHST tests:
48 | # t test difference of means:
49 | tInfo = t.test(myDataFrame[,yName]~myDataFrame[,xName])
50 | show(tInfo)
51 | # effect size and confidence interval on effect size:
52 | library(compute.es)
53 | tesInfo = tes( t=abs(tInfo$stat) ,
54 | n.1=sum(as.numeric(myDataFrame[,xName])==1) ,
55 | n.2=sum(as.numeric(myDataFrame[,xName])==2) , dig=4 )
56 | cat("\n\n\n")
57 | show( tesInfo[c("pval.d","l.d","d","u.d")] )
58 | cat("\n\n")
59 | # variances and test of ratio of variances:
60 | show(aggregate(myDataFrame[,yName]~myDataFrame[,xName],data=myDataFrame,sd))
61 | show(var.test(myDataFrame[,yName]~myDataFrame[,xName],data=myDataFrame))
62 |
--------------------------------------------------------------------------------
/2e/Kruschke-DBDA2E-ExerciseSolutions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/2e/Kruschke-DBDA2E-ExerciseSolutions.pdf
--------------------------------------------------------------------------------
/2e/Kruschke-DoingBayesian2ndEd-Figures.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/boboppie/kruschke-doing_bayesian_data_analysis/701202985fd1f305f8915b9be1876dca9459f1e6/2e/Kruschke-DoingBayesian2ndEd-Figures.pdf
--------------------------------------------------------------------------------
/2e/MetaAnalysisBetaBlocker.csv:
--------------------------------------------------------------------------------
1 | "StudyID","ControlDeaths","ControlTotal","TreatedDeaths","TreatedTotal"
2 | 1,3,39,3,38
3 | 2,14,116,7,114
4 | 3,11,93,5,69
5 | 4,127,1520,102,1533
6 | 5,27,365,28,355
7 | 6,6,52,4,59
8 | 7,152,939,98,945
9 | 8,48,471,60,632
10 | 9,37,282,25,278
11 | 10,188,1921,138,1916
12 | 11,52,583,64,873
13 | 12,47,266,45,263
14 | 13,16,293,9,291
15 | 14,45,883,57,858
16 | 15,31,147,25,154
17 | 16,38,213,33,207
18 | 17,12,122,28,251
19 | 18,6,154,8,151
20 | 19,3,134,6,174
21 | 20,40,218,32,209
22 | 21,43,364,27,391
23 | 22,39,674,22,680
24 |
--------------------------------------------------------------------------------
/2e/Movies.csv:
--------------------------------------------------------------------------------
1 | Title,Year,Length,Cast,Rating,Description
2 | A_Ticklish_Affair,1963,89,5,2,7
3 | Action_in_the_North_Atlantic,1943,127,7,3,9
4 | And_the_Ship_Sails_On,1984,138,7,3,15
5 | Autumn_Sonata,1978,97,5,3,11
6 | Bachelor_Apartment,1931,77,6,2.5,7
7 | Benson_Murder_Case,1930,69,8,2.5,10
8 | Black_Hand,1950,93,5,3,8
9 | Blaze,1989,119,8,2.5,15
10 | Blondie_Has_Servant_Trouble,1940,70,9,2.5,8
11 | Blondie_in_the_Dough,1947,69,9,2,8
12 | Brewster_McCloud,1970,101,9,3,11
13 | Calling_Philo_Vance,1940,62,6,2,10
14 | Car_Wash,1976,97,10,2.5,12
15 | City_Lights,1985,85,10,1,13
16 | Come_Out_Fighting,1945,62,9,1.5,9
17 | Conflict,1945,86,6,2.5,7
18 | Conquest,1937,112,10,3,10
19 | Dakota,1988,97,6,2,11
20 | Deadhead_Miles,1972,93,12,2.5,11
21 | Divided_Heart,1954,89,7,3,8
22 | Evergreen,1934,90,5,3,9
23 | Falcon_Strikes_Back,1943,66,9,2.5,9
24 | Find_the_Lady,1976,79,6,1.5,13
25 | Five_Golden_Hours,1961,90,7,2,9
26 | Flash_and_the_Firecat,1975,84,6,1.5,7
27 | Flight,1929,116,6,2.5,7
28 | Four_Jills_in_a_Jeep,1944,89,12,2.5,12
29 | Galileo,1973,145,11,3,13
30 | Hambone_and_Hillie,1984,89,8,2.5,8
31 | Hitler--Dead_or_Alive,1943,70,7,2,6
32 | Hold_Back_Tomorrow,1955,75,5,1.5,6
33 | House_Party_3,1994,94,8,1.5,12
34 | It_Came_from_Outer_Space,1953,81,6,3,12
35 | Jason's_Lyric,1994,119,9,2,16
36 | Jessica,1962,112,6,2.5,7
37 | Kit_Carson,1940,97,7,3,8
38 | Kronos,1957,78,5,2.5,11
39 | Lady_Dracula,1973,80,4,1,8
40 | Last_Plane_Out,1983,92,6,1.5,12
41 | Mad_Love,1995,95,12,1.5,13
42 | Manhunter,1986,119,7,3,21
43 | Memories_of_Me,1988,105,8,2,13
44 | Murder_by_Television,1935,60,5,1.5,8
45 | Night_of_the_Dark_Shadows,1971,97,6,1,11
46 | Okinawa,1952,67,6,2,6
47 | Once_a_Thief,1965,107,7,2,7
48 | One_Crazy_Summer,1986,93,8,2,12
49 | Our_Man_in_Havana,1960,107,7,2.5,8
50 | Secret_World,1969,94,5,2,7
51 | Secrets,1971,86,6,1.5,10
52 | Seminole_Uprising,1955,74,4,1.5,5
53 | She_Demons,1958,80,5,1,9
54 | Sherlock_Jr.,1924,45,6,4,13
55 | Shout_at_the_Devil,1976,119,5,2.5,10
56 | Single_Room_Furnished,1968,93,7,1.5,10
57 | Sleep_My_Love,1948,97,8,3,9
58 | Smash_Up:_The_Story_of_a_Woman,1947,103,6,3,14
59 | Spare_the_Rod,1961,93,6,2.5,7
60 | Station_West,1948,92,10,3,12
61 | Telefon,1977,102,7,3,11
62 | The_Abominable_Dr._Phibes,1971,94,5,3,9
63 | The_Amazing_Transparent_Man,1960,58,4,1,10
64 | The_Boogens,1981,95,6,1,8
65 | The_Boy_Who_Cried_Bitch,1991,101,10,3,12
66 | The_Chocolate_War,1988,103,7,3,13
67 | The_Cockeyed_Miracle,1946,81,5,2,7
68 | The_Competition,1980,129,8,3,10
69 | The_Curse_of_Bigfoot,1972,87,3,1,5
70 | The_Great_Waldo_Pepper,1975,107,8,3,11
71 | The_Hatter's_Ghost,1982,120,4,1.5,9
72 | The_Judge_and_the_Assassin,1975,130,5,3.5,9
73 | The_Last_Valley,1970,128,6,2,9
74 | The_Marriage_of_a_Young_Stockbroker,1971,95,6,2.5,14
75 | The_Miracle_Worker,1962,107,7,3.5,14
76 | The_Mutineers,1949,60,4,1.5,5
77 | The_Raven,1963,86,6,3,9
78 | The_Ravine,1969,97,6,2,7
79 | The_Revolt_of_Job,1983,97,6,3.5,9
80 | The_Romantic_Age,1949,86,6,2,7
81 | The_Siege_at_Red_River,1954,81,5,2.5,5
82 | The_Stone_Boy,1984,93,8,3.5,12
83 | The_Strip,1951,85,4,2,9
84 | The_Surrogate,1984,95,7,2.5,13
85 | The_Twinkle_in_God's_Eye,1955,73,5,2,7
86 | The_Ultimate_Warrior,1975,94,6,2.5,10
87 | The_Unholy_Three,1930,72,6,2.5,9
88 | The_Well,1951,85,7,3,8
89 | Tom_Dick_and_Harry,1941,86,7,3.5,11
90 | Triumph_of_the_Spirit,1989,121,7,3,12
91 | Uncle_Moses,1932,87,7,2.5,16
92 | Unsane,1982,100,6,2,12
93 | Valley_of_Gwangi,1969,95,5,2.5,11
94 | Valley_of_the_Dragons,1961,79,5,1.5,8
95 | Vicki,1953,85,7,2.5,9
96 | Volere_Volare,1991,92,7,2.5,17
97 | Warning_Shot,1967,100,13,3.5,12
98 | Whispering_Smith_vs._Scot._Yard,1951,77,5,2,9
99 | Windows,1980,96,4,1,9
100 | Windwalker,1980,108,5,2.5,11
101 | You_Only_Live_Twice,1967,116,9,2.5,14
102 |
--------------------------------------------------------------------------------
/2e/NonhomogVarData.csv:
--------------------------------------------------------------------------------
1 | "Group","Y"
2 | "A",97.7702139564945
3 | "A",99.9198717087243
4 | "A",92.372917320023
5 | "A",96.9456311267826
6 | "A",101.440603791142
7 | "A",80.659978995557
8 | "A",106.112220295441
9 | "A",99.6435187293738
10 | "A",95.9725981926379
11 | "A",98.1408795640525
12 | "A",91.8355950207805
13 | "A",93.2718826456248
14 | "A",86.1634907296565
15 | "A",91.2560358139671
16 | "A",114.865044721955
17 | "A",105.886445529482
18 | "A",109.474718521352
19 | "A",101.517223032432
20 | "A",82.3442790015467
21 | "A",103.818170941265
22 | "A",96.5693104543637
23 | "A",94.0152229117858
24 | "A",91.8946646132783
25 | "A",96.1094823822805
26 | "B",98.246778227903
27 | "B",98.7360062955954
28 | "B",98.7227078404973
29 | "B",99.9883246224481
30 | "B",99.2496148983615
31 | "B",99.7207710794589
32 | "B",100.408295427592
33 | "B",96.965348196178
34 | "B",96.759985150891
35 | "B",98.167841680243
36 | "B",98.5036142312359
37 | "B",99.2871913763967
38 | "B",99.0399275558388
39 | "B",100.245348310992
40 | "B",98.5509622829638
41 | "B",98.9841281946203
42 | "B",100.549598299614
43 | "B",99.065896948365
44 | "B",99.5895636527374
45 | "B",97.5324495694172
46 | "B",100.006808054313
47 | "B",99.06295617908
48 | "B",99.8981917844898
49 | "B",98.7176901407674
50 | "C",102.43258013734
51 | "C",102.198665031951
52 | "C",103.052658304532
53 | "C",101.604185761292
54 | "C",101.500252558098
55 | "C",100.014994429365
56 | "C",102.449030439403
57 | "C",101.895694334912
58 | "C",99.472960317358
59 | "C",101.346805971528
60 | "C",101.988298618537
61 | "C",100.954363025212
62 | "C",101.391178298421
63 | "C",102.067627518063
64 | "C",101.57225394574
65 | "C",103.029053363364
66 | "C",101.710951892104
67 | "C",102.725414147675
68 | "C",102.048686619974
69 | "C",101.917817303426
70 | "C",103.339808185578
71 | "C",104.102829950238
72 | "C",102.439910567349
73 | "C",102.743979278541
74 | "D",97.5613459383779
75 | "D",92.9122563329297
76 | "D",96.5003285750805
77 | "D",100.839423211782
78 | "D",88.359593282159
79 | "D",112.972841987129
80 | "D",107.960993744844
81 | "D",102.251333027749
82 | "D",104.962638864169
83 | "D",97.6206921198967
84 | "D",118.774521744858
85 | "D",103.618958343736
86 | "D",111.653278000427
87 | "D",107.563420463175
88 | "D",98.7748806074796
89 | "D",101.571444963255
90 | "D",101.873559499607
91 | "D",94.9422417129122
92 | "D",112.812661439696
93 | "D",118.450108037131
94 | "D",112.448128528836
95 | "D",96.1866629012484
96 | "D",107.365171656163
97 | "D",108.023515017357
98 |
--------------------------------------------------------------------------------
/2e/OrdinalProbitData-1grp-1.csv:
--------------------------------------------------------------------------------
1 | "Y"
2 | 1
3 | 1
4 | 1
5 | 1
6 | 1
7 | 1
8 | 1
9 | 1
10 | 1
11 | 1
12 | 1
13 | 1
14 | 1
15 | 1
16 | 1
17 | 1
18 | 1
19 | 1
20 | 1
21 | 1
22 | 1
23 | 1
24 | 1
25 | 1
26 | 1
27 | 1
28 | 1
29 | 1
30 | 1
31 | 1
32 | 1
33 | 1
34 | 1
35 | 1
36 | 1
37 | 1
38 | 1
39 | 1
40 | 1
41 | 1
42 | 1
43 | 1
44 | 1
45 | 1
46 | 1
47 | 1
48 | 1
49 | 1
50 | 1
51 | 1
52 | 1
53 | 1
54 | 1
55 | 1
56 | 1
57 | 1
58 | 1
59 | 1
60 | 2
61 | 2
62 | 2
63 | 2
64 | 2
65 | 2
66 | 2
67 | 2
68 | 2
69 | 2
70 | 2
71 | 2
72 | 2
73 | 2
74 | 2
75 | 3
76 | 3
77 | 3
78 | 3
79 | 3
80 | 3
81 | 3
82 | 3
83 | 3
84 | 3
85 | 3
86 | 3
87 | 4
88 | 4
89 | 4
90 | 4
91 | 4
92 | 4
93 | 4
94 | 4
95 | 5
96 | 5
97 | 5
98 | 5
99 | 6
100 | 6
101 | 7
102 |
--------------------------------------------------------------------------------
/2e/OrdinalProbitData-1grp-2.csv:
--------------------------------------------------------------------------------
1 | "Y"
2 | 1
3 | 1
4 | 1
5 | 1
6 | 1
7 | 1
8 | 2
9 | 2
10 | 2
11 | 2
12 | 2
13 | 2
14 | 2
15 | 2
16 | 2
17 | 2
18 | 2
19 | 2
20 | 2
21 | 2
22 | 2
23 | 2
24 | 2
25 | 2
26 | 2
27 | 2
28 | 2
29 | 2
30 | 2
31 | 2
32 | 2
33 | 3
34 | 3
35 | 3
36 | 3
37 | 3
38 | 3
39 | 3
40 | 3
41 | 3
42 | 4
43 | 4
44 | 4
45 | 4
46 | 4
47 | 4
48 | 4
49 | 5
50 | 5
51 | 5
52 | 5
53 | 5
54 | 5
55 | 5
56 | 5
57 | 6
58 | 6
59 | 6
60 | 6
61 | 6
62 | 6
63 | 6
64 | 6
65 | 6
66 | 6
67 | 6
68 | 6
69 | 6
70 | 7
71 | 7
72 |
--------------------------------------------------------------------------------
/2e/OrdinalProbitData1.csv:
--------------------------------------------------------------------------------
1 | "X","Y"
2 | "A",1
3 | "A",1
4 | "A",1
5 | "A",1
6 | "A",1
7 | "A",1
8 | "A",1
9 | "A",1
10 | "A",1
11 | "A",1
12 | "A",1
13 | "A",1
14 | "A",1
15 | "A",1
16 | "A",1
17 | "A",1
18 | "A",1
19 | "A",1
20 | "A",1
21 | "A",1
22 | "A",1
23 | "A",1
24 | "A",1
25 | "A",1
26 | "A",1
27 | "A",1
28 | "A",1
29 | "A",1
30 | "A",1
31 | "A",1
32 | "A",1
33 | "A",2
34 | "A",2
35 | "A",2
36 | "A",2
37 | "A",2
38 | "A",2
39 | "A",2
40 | "A",2
41 | "A",3
42 | "A",3
43 | "A",3
44 | "A",3
45 | "A",4
46 | "B",1
47 | "B",1
48 | "B",1
49 | "B",1
50 | "B",1
51 | "B",1
52 | "B",1
53 | "B",1
54 | "B",1
55 | "B",1
56 | "B",1
57 | "B",1
58 | "B",1
59 | "B",1
60 | "B",1
61 | "B",1
62 | "B",1
63 | "B",1
64 | "B",1
65 | "B",1
66 | "B",1
67 | "B",1
68 | "B",2
69 | "B",2
70 | "B",2
71 | "B",2
72 | "B",2
73 | "B",2
74 | "B",2
75 | "B",2
76 | "B",2
77 | "B",2
78 | "B",2
79 | "B",3
80 | "B",3
81 | "B",3
82 | "B",3
83 | "B",3
84 | "B",3
85 | "B",3
86 | "B",4
87 | "B",4
88 | "B",4
89 | "B",5
90 |
--------------------------------------------------------------------------------
/2e/RunningProportion.R:
--------------------------------------------------------------------------------
1 | N = 500 # Specify the total number of flips, denoted N.
2 | pHeads = 0.5 # Specify underlying probability of heads.
3 | # Flip a coin N times and compute the running proportion of heads at each flip.
4 | # Generate a random sample of N flips (heads=1, tails=0):
5 | flipSequence = sample( x=c(0,1), prob=c(1-pHeads,pHeads), size=N, replace=TRUE )
6 | # Compute the running proportion of heads:
7 | r = cumsum( flipSequence ) # Cumulative sum: Number of heads at each step.
8 | n = 1:N # Number of flips at each step.
9 | runProp = r / n # Component by component division.
10 | # Graph the running proportion:
11 | plot( n , runProp , type="o" , log="x" , col="skyblue" ,
12 | xlim=c(1,N) , ylim=c(0.0,1.0) , cex.axis=1.5 ,
13 | xlab="Flip Number" , ylab="Proportion Heads" , cex.lab=1.5 ,
14 | main="Running Proportion of Heads" , cex.main=1.5 )
15 | # Plot a dotted horizontal reference line:
16 | abline( h=pHeads , lty="dotted" )
17 | # Display the beginning of the flip sequence:
18 | flipLetters = paste( c("T","H")[flipSequence[1:10]+1] , collapse="" )
19 | displayString = paste0( "Flip Sequence = " , flipLetters , "..." )
20 | text( N , .9 , displayString , adj=c(1,0.5) , cex=1.3 )
21 | # Display the relative frequency at the end of the sequence.
22 | text( N , .8 , paste("End Proportion =",runProp[N]) , adj=c(1,0.5) , cex=1.3 )
--------------------------------------------------------------------------------
/2e/SeaweedData.csv:
--------------------------------------------------------------------------------
1 | SeaweedAmt,Zone,Grazer
2 | 11,A,f
3 | 24,A,f
4 | 14,B,f
5 | 31,B,f
6 | 52,C,f
7 | 59,C,f
8 | 83,D,f
9 | 89,D,f
10 | 33,E,f
11 | 34,E,f
12 | 39,F,f
13 | 52,F,f
14 | 43,G,f
15 | 53,G,f
16 | 30,H,f
17 | 37,H,f
18 | 10,A,fF
19 | 13,A,fF
20 | 10,B,fF
21 | 15,B,fF
22 | 44,C,fF
23 | 50,C,fF
24 | 57,D,fF
25 | 73,D,fF
26 | 26,E,fF
27 | 42,E,fF
28 | 38,F,fF
29 | 42,F,fF
30 | 29,G,fF
31 | 36,G,fF
32 | 11,H,fF
33 | 40,H,fF
34 | 4,A,L
35 | 4,A,L
36 | 7,B,L
37 | 8,B,L
38 | 28,C,L
39 | 58,C,L
40 | 27,D,L
41 | 35,D,L
42 | 11,E,L
43 | 33,E,L
44 | 16,F,L
45 | 31,F,L
46 | 6,G,L
47 | 8,G,L
48 | 15,H,L
49 | 17,H,L
50 | 3,A,Lf
51 | 5,A,Lf
52 | 3,B,Lf
53 | 6,B,Lf
54 | 9,C,Lf
55 | 31,C,Lf
56 | 21,D,Lf
57 | 57,D,Lf
58 | 5,E,Lf
59 | 9,E,Lf
60 | 26,F,Lf
61 | 43,F,Lf
62 | 4,G,Lf
63 | 12,G,Lf
64 | 12,H,Lf
65 | 18,H,Lf
66 | 1,A,LfF
67 | 2,A,LfF
68 | 3,B,LfF
69 | 5,B,LfF
70 | 6,C,LfF
71 | 9,C,LfF
72 | 7,D,LfF
73 | 22,D,LfF
74 | 5,E,LfF
75 | 6,E,LfF
76 | 10,F,LfF
77 | 17,F,LfF
78 | 5,G,LfF
79 | 14,G,LfF
80 | 5,H,LfF
81 | 7,H,LfF
82 | 14,A,None
83 | 23,A,None
84 | 22,B,None
85 | 35,B,None
86 | 67,C,None
87 | 82,C,None
88 | 94,D,None
89 | 95,D,None
90 | 34,E,None
91 | 53,E,None
92 | 58,F,None
93 | 75,F,None
94 | 19,G,None
95 | 47,G,None
96 | 53,H,None
97 | 61,H,None
98 |
--------------------------------------------------------------------------------
/2e/ShohatOphirKAMH2012dataReduced.csv:
--------------------------------------------------------------------------------
1 | Group,SubjectInGroup,NonEthanol3DayTotal,Ethanol3DayTotal,GrandTotal,PreferenceIndex
2 | MatedGrouped,1,93,64,157,-0.185
3 | MatedGrouped,2,46,74,120,0.233
4 | MatedGrouped,3,79,86,165,0.042
5 | MatedGrouped,4,94,68,162,-0.160
6 | MatedGrouped,5,56,88,144,0.222
7 | MatedGrouped,6,68,82,150,0.093
8 | MatedGrouped,7,140,60,200,-0.400
9 | MatedGrouped,8,93,53,146,-0.274
10 | MatedGrouped,9,98,74,172,-0.140
11 | MatedGrouped,10,74,62,136,-0.088
12 | RejectedIsolated,1,67,92,159,0.157
13 | RejectedIsolated,2,44,98,142,0.380
14 | RejectedIsolated,3,60,98,158,0.241
15 | RejectedIsolated,4,58,77,135,0.141
16 | RejectedIsolated,5,42,80,122,0.311
17 | RejectedIsolated,6,59,102,161,0.267
18 | RejectedIsolated,7,90,71,161,-0.118
19 | RejectedIsolated,8,28,133,161,0.652
20 | RejectedIsolated,9,75,109,184,0.185
21 | RejectedIsolated,10,76,103,179,0.151
22 |
--------------------------------------------------------------------------------
/2e/SimpleGraph.R:
--------------------------------------------------------------------------------
1 | x = seq( from = -2 , to = 2 , by = 0.1 ) # Specify vector of x values.
2 | y = x^2 # Specify corresponding y values.
3 | plot( x , y , col="skyblue" , type="l" ) # Plot the x,y points as a blue line.
4 |
--------------------------------------------------------------------------------
/2e/SplitPlotAgriData.csv:
--------------------------------------------------------------------------------
1 | "Field","Till","Fert","Yield"
2 | 1,"Chisel","Broad",119
3 | 1,"Chisel","Deep",130
4 | 1,"Chisel","Surface",123
5 | 2,"Chisel","Broad",135
6 | 2,"Chisel","Deep",148
7 | 2,"Chisel","Surface",134
8 | 3,"Chisel","Broad",140
9 | 3,"Chisel","Deep",146
10 | 3,"Chisel","Surface",142
11 | 4,"Chisel","Broad",126
12 | 4,"Chisel","Deep",132
13 | 4,"Chisel","Surface",131
14 | 5,"Chisel","Broad",128
15 | 5,"Chisel","Deep",141
16 | 5,"Chisel","Surface",153
17 | 6,"Chisel","Broad",117
18 | 6,"Chisel","Deep",130
19 | 6,"Chisel","Surface",123
20 | 7,"Chisel","Broad",104
21 | 7,"Chisel","Deep",126
22 | 7,"Chisel","Surface",120
23 | 8,"Chisel","Broad",108
24 | 8,"Chisel","Deep",117
25 | 8,"Chisel","Surface",118
26 | 9,"Chisel","Broad",117
27 | 9,"Chisel","Deep",129
28 | 9,"Chisel","Surface",127
29 | 10,"Chisel","Broad",137
30 | 10,"Chisel","Deep",143
31 | 10,"Chisel","Surface",144
32 | 11,"Chisel","Broad",146
33 | 11,"Chisel","Deep",137
34 | 11,"Chisel","Surface",134
35 | 12,"Chisel","Broad",114
36 | 12,"Chisel","Deep",126
37 | 12,"Chisel","Surface",128
38 | 13,"Moldbrd","Broad",143
39 | 13,"Moldbrd","Deep",159
40 | 13,"Moldbrd","Surface",148
41 | 14,"Moldbrd","Broad",146
42 | 14,"Moldbrd","Deep",164
43 | 14,"Moldbrd","Surface",154
44 | 15,"Moldbrd","Broad",133
45 | 15,"Moldbrd","Deep",132
46 | 15,"Moldbrd","Surface",143
47 | 16,"Moldbrd","Broad",160
48 | 16,"Moldbrd","Deep",175
49 | 16,"Moldbrd","Surface",167
50 | 17,"Moldbrd","Broad",137
51 | 17,"Moldbrd","Deep",145
52 | 17,"Moldbrd","Surface",148
53 | 18,"Moldbrd","Broad",133
54 | 18,"Moldbrd","Deep",142
55 | 18,"Moldbrd","Surface",132
56 | 19,"Moldbrd","Broad",146
57 | 19,"Moldbrd","Deep",153
58 | 19,"Moldbrd","Surface",137
59 | 20,"Moldbrd","Broad",147
60 | 20,"Moldbrd","Deep",161
61 | 20,"Moldbrd","Surface",153
62 | 21,"Moldbrd","Broad",124
63 | 21,"Moldbrd","Deep",138
64 | 21,"Moldbrd","Surface",133
65 | 22,"Moldbrd","Broad",139
66 | 22,"Moldbrd","Deep",141
67 | 22,"Moldbrd","Surface",145
68 | 23,"Ridge","Broad",115
69 | 23,"Ridge","Deep",142
70 | 23,"Ridge","Surface",148
71 | 24,"Ridge","Broad",156
72 | 24,"Ridge","Deep",174
73 | 24,"Ridge","Surface",174
74 | 25,"Ridge","Broad",120
75 | 25,"Ridge","Deep",144
76 | 25,"Ridge","Surface",145
77 | 26,"Ridge","Broad",110
78 | 26,"Ridge","Deep",128
79 | 26,"Ridge","Surface",147
80 | 27,"Ridge","Broad",130
81 | 27,"Ridge","Deep",153
82 | 27,"Ridge","Surface",154
83 | 28,"Ridge","Broad",119
84 | 28,"Ridge","Deep",165
85 | 28,"Ridge","Surface",150
86 | 29,"Ridge","Broad",120
87 | 29,"Ridge","Deep",144
88 | 29,"Ridge","Surface",135
89 | 30,"Ridge","Broad",120
90 | 30,"Ridge","Deep",148
91 | 30,"Ridge","Surface",140
92 | 31,"Ridge","Broad",143
93 | 31,"Ridge","Deep",176
94 | 31,"Ridge","Surface",169
95 | 32,"Ridge","Broad",122
96 | 32,"Ridge","Deep",160
97 | 32,"Ridge","Surface",158
98 | 33,"Ridge","Broad",153
99 | 33,"Ridge","Deep",176
100 | 33,"Ridge","Surface",165
101 |
--------------------------------------------------------------------------------
/2e/Stan-Ydich-Xnom1subj-MbernBeta-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ydich-Xnom1subj-MbernBeta.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data
8 | myData = read.csv("z15N50.csv")
9 | #-------------------------------------------------------------------------------
10 | # Load the functions genMCMC, smryMCMC, and plotMCMC:
11 | source("Stan-Ydich-Xnom1subj-MbernBeta.R")
12 | #-------------------------------------------------------------------------------
13 | # Optional: Specify filename root and graphical format for saving output.
14 | # Otherwise specify as NULL or leave saveName and saveType arguments
15 | # out of function calls.
16 | fileNameRoot = "Stan-Ydich-Xnom1subj-MbernBeta-"
17 | graphFileType = "eps"
18 | #-------------------------------------------------------------------------------
19 | # Generate the MCMC chain:
20 | mcmcCoda = genMCMC( data=myData , numSavedSteps=10000 , saveName=fileNameRoot )
21 | #-------------------------------------------------------------------------------
22 | # Display diagnostics of chain, for specified parameters:
23 | parameterNames = varnames(mcmcCoda) # get all parameter names
24 | for ( parName in parameterNames ) {
25 | diagMCMC( mcmcCoda , parName=parName ,
26 | saveName=fileNameRoot , saveType=graphFileType )
27 | }
28 | #-------------------------------------------------------------------------------
29 | # Get summary statistics of chain:
30 | summaryInfo = smryMCMC( mcmcCoda , compVal=0.5 , rope=c(0.45,0.55) ,
31 | saveName=fileNameRoot )
32 | # Display posterior information:
33 | plotMCMC( mcmcCoda , data=myData , # compVal=0.5 , rope=c(0.45,0.55) ,
34 | saveName=fileNameRoot , saveType=graphFileType )
35 | #-------------------------------------------------------------------------------
36 | # Use Stan display functions instead of DBDA2E functions:
37 | # Load the stanFit object that was saved by genMCMC:
38 | load("Stan-Ydich-Xnom1subj-MbernBeta-StanFit.Rdata")
39 | # Display information:
40 | show(stanFit)
41 | openGraph()
42 | traceplot(stanFit,pars=c("theta"))
43 | openGraph()
44 | plot(stanFit,pars=c("theta"))
45 |
--------------------------------------------------------------------------------
/2e/Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data
8 | myData = read.csv("TherapeuticTouchData.csv")
9 | # N.B.: The functions below expect the data to be a data frame,
10 | # with one component named y being a vector of integer 0,1 values,
11 | # and one component named s being a factor of subject identifiers.
12 | #-------------------------------------------------------------------------------
13 | # Load the relevant model into R's working memory:
14 | source("Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa.R")
15 | #-------------------------------------------------------------------------------
16 | # Optional: Specify filename root and graphical format for saving output.
17 | # Otherwise specify as NULL or leave saveName and saveType arguments
18 | # out of function calls.
19 | fileNameRoot = "Stan-Ydich-XnomSsubj-MbernBetaOmegaKappa-"
20 | graphFileType = "eps"
21 | #-------------------------------------------------------------------------------
22 | # Generate the MCMC chain:
23 | startTime = proc.time()
24 | mcmcCoda = genMCMC( data=myData , sName="s" , yName="y" ,
25 | numSavedSteps=12000 , saveName=fileNameRoot , thinSteps=10 )
26 | stopTime = proc.time()
27 | duration = stopTime - startTime
28 | show(duration)
29 | #-------------------------------------------------------------------------------
30 | # Display diagnostics of chain, for specified parameters:
31 | parameterNames = varnames(mcmcCoda) # get all parameter names for reference
32 | for ( parName in c("omega","kappa","theta[1]","theta[2]") ) {
33 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
34 | saveName=fileNameRoot , saveType=graphFileType )
35 | }
36 | #-------------------------------------------------------------------------------
37 | # Get summary statistics of chain:
38 | summaryInfo = smryMCMC( mcmcCoda , compVal=0.5 ,
39 | diffIdVec=c(1,14,28), compValDiff=0.0,
40 | saveName=fileNameRoot )
41 | # Display posterior information:
42 | plotMCMC( mcmcCoda , data=myData , compVal=0.5 , #rope=c(0.45,0.55) ,
43 | diffIdVec=c(1,14,28), compValDiff=0.0, #ropeDiff = c(-0.05,0.05) ,
44 | saveName=fileNameRoot , saveType=graphFileType )
45 | #-------------------------------------------------------------------------------
46 | # Using Stan display functions instead of DBDA2E functions:
47 | # Load the stanFit object that was saved by genMCMC:
48 | load(paste0(fileNameRoot,"StanFit.Rdata"))
49 | # Display information:
50 | show(stanFit)
51 | openGraph()
52 | traceplot(stanFit,pars= c("omega","kappa","theta[1]","theta[2]"))
53 | openGraph()
54 | plot(stanFit)
55 |
--------------------------------------------------------------------------------
/2e/Stan-Ymet-Xmet-Mrobust-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ymet-Xmet-Mrobust.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load data file and specity column names of x (predictor) and y (predicted):
8 | myData = read.csv( file="HtWtData300.csv" )
9 | xName = "height" ; yName = "weight"
10 | fileNameRoot = "HtWtData300-Stan-"
11 | graphFileType = "eps"
12 | #-------------------------------------------------------------------------------
13 | # Load the relevant model into R's working memory:
14 | source("Stan-Ymet-Xmet-Mrobust.R")
15 | #-------------------------------------------------------------------------------
16 | # Generate the MCMC chain:
17 | mcmcCoda = genMCMC( data=myData , xName=xName , yName=yName ,
18 | numSavedSteps=20000 , saveName=fileNameRoot )
19 | #-------------------------------------------------------------------------------
20 | # Display diagnostics of chain, for specified parameters:
21 | parameterNames = varnames(mcmcCoda) # get all parameter names
22 | for ( parName in parameterNames ) {
23 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
24 | saveName=fileNameRoot , saveType=graphFileType )
25 | }
26 | #-------------------------------------------------------------------------------
27 | # Get summary statistics of chain:
28 | summaryInfo = smryMCMC( mcmcCoda ,
29 | compValBeta1=0.0 , ropeBeta1=c(-0.5,0.5) ,
30 | saveName=fileNameRoot )
31 | show(summaryInfo)
32 | # Display posterior information:
33 | plotMCMC( mcmcCoda , data=myData , xName=xName , yName=yName ,
34 | compValBeta1=0.0 , ropeBeta1=c(-0.5,0.5) ,
35 | pairsPlot=TRUE , showCurve=FALSE ,
36 | saveName=fileNameRoot , saveType=graphFileType )
37 | #-------------------------------------------------------------------------------
38 |
--------------------------------------------------------------------------------
/2e/Stan-Ymet-XmetSsubj-MrobustHierQuadWt-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ymet-XmetSsubj-MrobustHierQuadWt.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load data file and specity column names of x (predictor) and y (predicted):
8 |
9 | # myData = read.csv( file="IncomeFamszState3yr.csv" , comment.char="#")
10 | # xName = "FamilySize" ; yName = "MedianIncome" ; sName="State" ; wName="SampErr"
11 | # fileNameRoot = "IncomeFamszState3yr-Stan-"
12 |
13 | myData = read.csv( file="HierLinRegressData.csv" )
14 | xName = "X" ; yName = "Y" ; sName="Subj" ; wName=NULL
15 | fileNameRoot = "HierLinRegressData-Quad-Stan-"
16 |
17 | # myData = read.csv( file="BugsRatsData.csv" )
18 | # xName = "Day" ; yName = "Weight" ; sName="Subj" ; wName=NULL
19 | # fileNameRoot = "BugsRatsData-Quad-Stan-"
20 |
21 | graphFileType = "eps"
22 | #-------------------------------------------------------------------------------
23 | # Load the relevant model into R's working memory:
24 | source("Stan-Ymet-XmetSsubj-MrobustHierQuadWt.R")
25 | #-------------------------------------------------------------------------------
26 | # Generate the MCMC chain:
27 | #startTime = proc.time()
28 | mcmcCoda = genMCMC( data=myData ,
29 | xName=xName , yName=yName , sName=sName , wName=wName ,
30 | numSavedSteps=12000 , thinSteps=5 , saveName=fileNameRoot )
31 | #stopTime = proc.time()
32 | #duration = stopTime - startTime
33 | #show(duration)
34 | # #-------------------------------------------------------------------------------
35 | # # Display diagnostics of chain, for specified parameters:
36 | parameterNames = varnames(mcmcCoda) # get all parameter names
37 | for ( parName in c("beta0mu","beta1mu","beta2mu","nu","sigma",
38 | "beta0[1]","beta1[1]","beta2[1]") ) {
39 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
40 | saveName=fileNameRoot , saveType=graphFileType )
41 | }
42 | #-------------------------------------------------------------------------------
43 | # Get summary statistics of chain:
44 | summaryInfo = smryMCMC( mcmcCoda , saveName=fileNameRoot )
45 | show(summaryInfo)
46 | # Display posterior information:
47 | plotMCMC( mcmcCoda , data=myData ,
48 | xName=xName , yName=yName , sName=sName , wName=wName ,
49 | pairsPlot=TRUE , showCurve=FALSE ,
50 | saveName=fileNameRoot , saveType=graphFileType )
51 | #-------------------------------------------------------------------------------
52 |
--------------------------------------------------------------------------------
/2e/Stan-Ymet-Xnom1grp-Mrobust-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ymet-Xnom1grp-Mrobust.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 | myDataFrame = read.csv( file="TwoGroupIQ.csv" )
9 | # For purposes of this one-group example, use data from Smart Drug group:
10 | myData = myDataFrame$Score[myDataFrame$Group=="Smart Drug"]
11 | #-------------------------------------------------------------------------------
12 | # Load the relevant model into R's working memory:
13 | source("Stan-Ymet-Xnom1grp-Mrobust.R")
14 | #-------------------------------------------------------------------------------
15 | # Optional: Specify filename root and graphical format for saving output.
16 | # Otherwise specify as NULL or leave saveName and saveType arguments
17 | # out of function calls.
18 | fileNameRoot = "OneGroupIQrobust-Stan-"
19 | graphFileType = "eps"
20 | #-------------------------------------------------------------------------------
21 | # Generate the MCMC chain:
22 | mcmcCoda = genMCMC( data=myData , numSavedSteps=20000 , saveName=fileNameRoot )
23 | #-------------------------------------------------------------------------------
24 | # Display diagnostics of chain, for specified parameters:
25 | parameterNames = varnames(mcmcCoda) # get all parameter names
26 | for ( parName in parameterNames ) {
27 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
28 | saveName=fileNameRoot , saveType=graphFileType )
29 | }
30 | #-------------------------------------------------------------------------------
31 | # Get summary statistics of chain:
32 | summaryInfo = smryMCMC( mcmcCoda ,
33 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
34 | compValSigma=15.0 , ropeSigma=c(14,16) ,
35 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
36 | saveName=fileNameRoot )
37 | show(summaryInfo)
38 | # Display posterior information:
39 | plotMCMC( mcmcCoda , data=myData ,
40 | compValMu=100.0 , ropeMu=c(99.0,101.0) ,
41 | compValSigma=15.0 , ropeSigma=c(14,16) ,
42 | compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
43 | pairsPlot=TRUE , showCurve=FALSE ,
44 | saveName=fileNameRoot , saveType=graphFileType )
45 | #-------------------------------------------------------------------------------
46 |
--------------------------------------------------------------------------------
/2e/Stan-Ymet-Xnom2grp-MrobustHet-Example.R:
--------------------------------------------------------------------------------
1 | # Example for Stan-Ymet-Xnom2grp-MrobustHet.R
2 | #-------------------------------------------------------------------------------
3 | # Optional generic preliminaries:
4 | graphics.off() # This closes all of R's graphics windows.
5 | rm(list=ls()) # Careful! This clears all of R's memory!
6 | #-------------------------------------------------------------------------------
7 | # Load The data file
8 | myDataFrame = read.csv( file="TwoGroupIQ.csv" )
9 | #-------------------------------------------------------------------------------
10 | # Load the relevant model into R's working memory:
11 | source("Stan-Ymet-Xnom2grp-MrobustHet.R")
12 | #-------------------------------------------------------------------------------
13 | # Optional: Specify filename root and graphical format for saving output.
14 | # Otherwise specify as NULL or leave saveName and saveType arguments
15 | # out of function calls.
16 | fileNameRoot = "TwoGroupIQrobustHet-Stan-"
17 | graphFileType = "eps"
18 | #-------------------------------------------------------------------------------
19 | # Generate the MCMC chain:
20 | mcmcCoda = genMCMC( datFrm=myDataFrame , yName="Score" , xName="Group" ,
21 | numSavedSteps=20000 , saveName=fileNameRoot )
22 | #-------------------------------------------------------------------------------
23 | # Display diagnostics of chain, for specified parameters:
24 | parameterNames = varnames(mcmcCoda) # get all parameter names
25 | for ( parName in parameterNames ) {
26 | diagMCMC( codaObject=mcmcCoda , parName=parName ,
27 | saveName=fileNameRoot , saveType=graphFileType )
28 | }
29 | #-------------------------------------------------------------------------------
30 | # Get summary statistics of chain:
31 | summaryInfo = smryMCMC( mcmcCoda , RopeMuDiff=c(-0.5,0.5) ,
32 | RopeSdDiff=c(-0.5,0.5) , RopeEff=c(-0.1,0.1) ,
33 | saveName=fileNameRoot )
34 | show(summaryInfo)
35 | # Display posterior information:
36 | plotMCMC( mcmcCoda , datFrm=myDataFrame , yName="Score" , xName="Group" ,
37 | RopeMuDiff=c(-0.5,0.5) , RopeSdDiff=c(-0.5,0.5), RopeEff=c(-0.1,0.1) ,
38 | pairsPlot=TRUE , saveName=fileNameRoot , saveType=graphFileType )
39 | #-------------------------------------------------------------------------------
40 |
--------------------------------------------------------------------------------
/2e/TwoGroupIQ.csv:
--------------------------------------------------------------------------------
1 | "Score","Group"
2 | 102,"Smart Drug"
3 | 107,"Smart Drug"
4 | 92,"Smart Drug"
5 | 101,"Smart Drug"
6 | 110,"Smart Drug"
7 | 68,"Smart Drug"
8 | 119,"Smart Drug"
9 | 106,"Smart Drug"
10 | 99,"Smart Drug"
11 | 103,"Smart Drug"
12 | 90,"Smart Drug"
13 | 93,"Smart Drug"
14 | 79,"Smart Drug"
15 | 89,"Smart Drug"
16 | 137,"Smart Drug"
17 | 119,"Smart Drug"
18 | 126,"Smart Drug"
19 | 110,"Smart Drug"
20 | 71,"Smart Drug"
21 | 114,"Smart Drug"
22 | 100,"Smart Drug"
23 | 95,"Smart Drug"
24 | 91,"Smart Drug"
25 | 99,"Smart Drug"
26 | 97,"Smart Drug"
27 | 106,"Smart Drug"
28 | 106,"Smart Drug"
29 | 129,"Smart Drug"
30 | 115,"Smart Drug"
31 | 124,"Smart Drug"
32 | 137,"Smart Drug"
33 | 73,"Smart Drug"
34 | 69,"Smart Drug"
35 | 95,"Smart Drug"
36 | 102,"Smart Drug"
37 | 116,"Smart Drug"
38 | 111,"Smart Drug"
39 | 134,"Smart Drug"
40 | 102,"Smart Drug"
41 | 110,"Smart Drug"
42 | 139,"Smart Drug"
43 | 112,"Smart Drug"
44 | 122,"Smart Drug"
45 | 84,"Smart Drug"
46 | 129,"Smart Drug"
47 | 112,"Smart Drug"
48 | 127,"Smart Drug"
49 | 106,"Smart Drug"
50 | 113,"Smart Drug"
51 | 109,"Smart Drug"
52 | 208,"Smart Drug"
53 | 114,"Smart Drug"
54 | 107,"Smart Drug"
55 | 50,"Smart Drug"
56 | 169,"Smart Drug"
57 | 133,"Smart Drug"
58 | 50,"Smart Drug"
59 | 97,"Smart Drug"
60 | 139,"Smart Drug"
61 | 72,"Smart Drug"
62 | 100,"Smart Drug"
63 | 144,"Smart Drug"
64 | 112,"Smart Drug"
65 | 109,"Placebo"
66 | 98,"Placebo"
67 | 106,"Placebo"
68 | 101,"Placebo"
69 | 100,"Placebo"
70 | 111,"Placebo"
71 | 117,"Placebo"
72 | 104,"Placebo"
73 | 106,"Placebo"
74 | 89,"Placebo"
75 | 84,"Placebo"
76 | 88,"Placebo"
77 | 94,"Placebo"
78 | 78,"Placebo"
79 | 108,"Placebo"
80 | 102,"Placebo"
81 | 95,"Placebo"
82 | 99,"Placebo"
83 | 90,"Placebo"
84 | 116,"Placebo"
85 | 97,"Placebo"
86 | 107,"Placebo"
87 | 102,"Placebo"
88 | 91,"Placebo"
89 | 94,"Placebo"
90 | 95,"Placebo"
91 | 86,"Placebo"
92 | 108,"Placebo"
93 | 115,"Placebo"
94 | 108,"Placebo"
95 | 88,"Placebo"
96 | 102,"Placebo"
97 | 102,"Placebo"
98 | 120,"Placebo"
99 | 112,"Placebo"
100 | 100,"Placebo"
101 | 105,"Placebo"
102 | 105,"Placebo"
103 | 88,"Placebo"
104 | 82,"Placebo"
105 | 111,"Placebo"
106 | 96,"Placebo"
107 | 92,"Placebo"
108 | 109,"Placebo"
109 | 91,"Placebo"
110 | 92,"Placebo"
111 | 123,"Placebo"
112 | 61,"Placebo"
113 | 59,"Placebo"
114 | 105,"Placebo"
115 | 184,"Placebo"
116 | 82,"Placebo"
117 | 138,"Placebo"
118 | 99,"Placebo"
119 | 93,"Placebo"
120 | 93,"Placebo"
121 | 72,"Placebo"
122 |
--------------------------------------------------------------------------------
/2e/minNforHDIpower-example.R:
--------------------------------------------------------------------------------
1 |
2 | source("minNforHDIpower.R")
3 |
4 | # Specify desired powers:
5 | desPow = seq(.7,.9,by=0.1)
6 | # Specify generating modes:
7 | genMod = seq(0.60,0.85,by=0.05)
8 |
9 | # HDI excludes ROPE around nullVal:
10 | # Declare matrix for storing results:
11 | sampSizeMatrix = matrix( NA , nrow=length(desPow) , ncol=length(genMod) ,
12 | dimnames=list("Power"=desPow,"Gen.Mode"=genMod) )
13 | # Compute sample size for all combinations of desired powers and modes:
14 | for ( desPowIdx in 1:length(desPow) ) {
15 | for ( genModIdx in 1:length(genMod) ) {
16 | sampSize = minNforHDIpower( genPriorMode=genMod[genModIdx], genPriorN=2000,
17 | HDImaxwid=NULL, nullVal=0.5, ROPE=c(0.48,0.52),
18 | desiredPower=desPow[desPowIdx] ,
19 | audPriorMode=0.5 , audPriorN=2 ,
20 | HDImass=0.95 , initSampSize=5 , verbose=FALSE )
21 | sampSizeMatrix[desPowIdx,genModIdx ] = sampSize
22 | show(sampSizeMatrix)
23 | }
24 | }
25 | sampSizeExclNull = sampSizeMatrix
26 | show(sampSizeExclNull)
27 |
28 | # HDI has maximum width:
29 | # Declare matrix for storing results:
30 | sampSizeMatrix = matrix( NA , nrow=length(desPow) , ncol=length(genMod) ,
31 | dimnames=list("Power"=desPow,"Gen.Mode"=genMod) )
32 | # Compute sample size for all combinations of desired powers and modes:
33 | for ( desPowIdx in 1:length(desPow) ) {
34 | for ( genModIdx in 1:length(genMod) ) {
35 | sampSize = minNforHDIpower( genPriorMode=genMod[genModIdx], genPriorN=10,
36 | HDImaxwid=0.20, nullVal=NULL, ROPE=NULL,
37 | desiredPower=desPow[desPowIdx] ,
38 | audPriorMode=0.5 , audPriorN=2 ,
39 | HDImass=0.95 , initSampSize=50 , verbose=FALSE )
40 | sampSizeMatrix[desPowIdx,genModIdx ] = sampSize
41 | show(sampSizeMatrix)
42 | }
43 | }
44 | sampSizeMaxHdiWid = sampSizeMatrix
45 | show(sampSizeExclNull)
46 | show(sampSizeMaxHdiWid)
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/2e/minNforHDIpower.R:
--------------------------------------------------------------------------------
1 | minNforHDIpower = function( genPriorMode , genPriorN ,
2 | HDImaxwid=NULL , nullVal=NULL ,
3 | ROPE=c(max(0,nullVal-.02),min(1,nullVal+.02)) ,
4 | desiredPower=0.8 , audPriorMode=0.5 , audPriorN=2 ,
5 | HDImass=0.95 , initSampSize=20 , verbose=TRUE ) {
6 | # Check for argument consistency:
7 | if ( !xor( is.null(HDImaxwid) , is.null(nullVal) ) ) {
8 | stop("One and only one of HDImaxwid and nullVal must be specified.")
9 | }
10 | # Load HDIofICDF function if not already present:
11 | if ( !exists("HDIofICDF") ) source("DBDA2E-utilities.R")
12 | # Convert prior mode and N to a,b parameters of beta distribution:
13 | genPriorA = genPriorMode * (genPriorN-2) + 1
14 | genPriorB = ( 1.0 - genPriorMode ) * (genPriorN-2) + 1
15 | audPriorA = audPriorMode * (audPriorN-2) + 1
16 | audPriorB = ( 1.0 - audPriorMode ) * (audPriorN-2) + 1
17 | # Initialize loop for incrementing sampleSize:
18 | sampleSize = initSampSize
19 | notPowerfulEnough = TRUE
20 | # Increment sampleSize until desired power is achieved:
21 | while( notPowerfulEnough ) {
22 | zvec = 0:sampleSize # vector of all possible z values for N flips.
23 | # Compute probability of each z value for data-generating prior:
24 | pzvec = exp( lchoose( sampleSize , zvec )
25 | + lbeta( zvec + genPriorA , sampleSize-zvec + genPriorB )
26 | - lbeta( genPriorA , genPriorB ) )
27 | # For each z value, compute posterior HDI:
28 | # hdiMat will hold HDI limits for each z:
29 | hdiMat = matrix( 0 , nrow=length(zvec) , ncol=2 )
30 | for ( zIdx in 1:length(zvec) ) {
31 | z = zvec[zIdx]
32 | hdiMat[zIdx,] = HDIofICDF( qbeta ,
33 | shape1 = z + audPriorA ,
34 | shape2 = sampleSize - z + audPriorB ,
35 | credMass = HDImass )
36 | }
37 | # Compute HDI widths:
38 | hdiWid = hdiMat[,2] - hdiMat[,1]
39 | # Sum the probabilities of outcomes with satisfactory HDI widths:
40 | if ( !is.null( HDImaxwid ) ) {
41 | powerHDI = sum( pzvec[ hdiWid < HDImaxwid ] )
42 | }
43 | # Sum the probabilities of outcomes with HDI excluding ROPE:
44 | if ( !is.null( nullVal ) ) {
45 | powerHDI = sum( pzvec[ hdiMat[,1] > ROPE[2] | hdiMat[,2] < ROPE[1] ] )
46 | }
47 | if ( verbose ) {
48 | cat( " For sample size = ", sampleSize , ", power = " , powerHDI ,
49 | "\n" , sep="" ) ; flush.console()
50 | }
51 | if ( powerHDI > desiredPower ) { # If desired power is attained,
52 | notPowerfulEnough = FALSE # set flag to stop,
53 | } else { # otherwise
54 | sampleSize = sampleSize + 1 # increment the sample size.
55 | }
56 | } # End while( notPowerfulEnough ).
57 | # Return the sample size that achieved the desired power:
58 | return( sampleSize )
59 | } # End of function.
60 |
--------------------------------------------------------------------------------
/2e/z15N50.csv:
--------------------------------------------------------------------------------
1 | "y"
2 | 0
3 | 1
4 | 0
5 | 0
6 | 0
7 | 0
8 | 0
9 | 0
10 | 0
11 | 0
12 | 1
13 | 0
14 | 0
15 | 0
16 | 1
17 | 1
18 | 1
19 | 0
20 | 0
21 | 1
22 | 0
23 | 0
24 | 0
25 | 0
26 | 1
27 | 1
28 | 0
29 | 0
30 | 0
31 | 0
32 | 0
33 | 1
34 | 0
35 | 1
36 | 0
37 | 1
38 | 0
39 | 0
40 | 0
41 | 1
42 | 0
43 | 0
44 | 1
45 | 1
46 | 0
47 | 1
48 | 0
49 | 0
50 | 0
51 | 0
52 |
--------------------------------------------------------------------------------
/2e/z6N8z2N7.csv:
--------------------------------------------------------------------------------
1 | "y","s"
2 | "1","Reginald"
3 | "0","Reginald"
4 | "1","Reginald"
5 | "1","Reginald"
6 | "1","Reginald"
7 | "1","Reginald"
8 | "1","Reginald"
9 | "0","Reginald"
10 | "0","Tony"
11 | "0","Tony"
12 | "1","Tony"
13 | "0","Tony"
14 | "0","Tony"
15 | "1","Tony"
16 | "0","Tony"
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | kruschke-doing-bayesian-data-analysis
2 | =====================================
3 |
4 | John K. Kruschke's Doing Bayesian Data Analysis: A Tutorial with R and BUGS (1e) / A Tutorial with R, JAGS, and Stan (2e)
5 |
6 | I enjoy reading this book very much. The [homepage for the book is here](https://sites.google.com/site/doingbayesiandataanalysis/). Author's [homepage is here](http://www.indiana.edu/~kruschke/).
7 |
--------------------------------------------------------------------------------