├── DESCRIPTION ├── MD5 ├── NAMESPACE ├── R ├── BayesFactors.R ├── HDPHMMnegbin.R ├── HDPHMMpoisson.R ├── HDPHSMMnegbin.R ├── HMMpanelFE.R ├── HMMpanelRE.R ├── MCMCSVDreg.R ├── MCMCbinaryChange.R ├── MCMCdynamicEI.R ├── MCMCdynamicIRT1d-b.R ├── MCMCdynamicIRT1d.R ├── MCMCfactanal.R ├── MCMChierBetaBinom.R ├── MCMChierEI.R ├── MCMChlogit.R ├── MCMChpoisson.R ├── MCMChregress.R ├── MCMCirt1d.R ├── MCMCirtHier1d.R ├── MCMCirtKd.R ├── MCMCirtKdRob.R ├── MCMClogit.R ├── MCMCmetrop1R.R ├── MCMCmixfactanal.R ├── MCMCmnl.R ├── MCMCnegbin.R ├── MCMCnegbinChange.R ├── MCMCoprobit.R ├── MCMCoprobitChange.R ├── MCMCordfactanal.R ├── MCMCpack-package.R ├── MCMCpaircompare.R ├── MCMCpaircompare2d.R ├── MCMCpaircompare2dDP.R ├── MCMCpoisson.R ├── MCMCpoissonChange.R ├── MCMCprobit.R ├── MCMCprobitChange.R ├── MCMCquantreg.R ├── MCMCregress.R ├── MCMCregressChange.R ├── MCMCresidualBreakAnalysis.R ├── MCMCtobit.R ├── MCmodels.R ├── SSVSquantreg.R ├── SSVSquantregsummary.R ├── automate.R ├── btsutil.R ├── data.R ├── distn.R ├── hdp-utils.R ├── hidden-hmodels.R ├── hidden.R ├── make.breaklist.R ├── procrust.R ├── scythe.R ├── testpanelGroupBreak.R ├── testpanelSubjectBreak.R ├── tomog.R ├── utility.R └── zzz.R ├── README ├── build └── partial.rdb ├── cleanup ├── configure ├── configure.ac ├── data ├── Euro2016.rda ├── Nethvote.rda ├── PErisk.rda ├── Rehnquist.rda ├── Senate.rda └── SupremeCourt.rda ├── inst ├── CITATION └── HISTORY.txt ├── man ├── BayesFactor.Rd ├── Dirichlet.Rd ├── Euro2016.Rd ├── HDPHMMnegbin.Rd ├── HDPHMMpoisson.Rd ├── HDPHSMMnegbin.Rd ├── HMMpanelFE.Rd ├── HMMpanelRE.Rd ├── InvGamma.Rd ├── InvWishart.Rd ├── MCMCSVDreg.Rd ├── MCMCbinaryChange.Rd ├── MCMCdynamicEI.Rd ├── MCMCdynamicIRT1d.Rd ├── MCMCfactanal.Rd ├── MCMChierEI.Rd ├── MCMChlogit.Rd ├── MCMChpoisson.Rd ├── MCMChregress.Rd ├── MCMCirt1d.Rd ├── MCMCirtHier1d.Rd ├── MCMCirtKd.Rd ├── MCMCirtKdRob.Rd ├── MCMClogit.Rd ├── MCMCmetrop1R.Rd ├── MCMCmixfactanal.Rd ├── MCMCmnl.Rd ├── MCMCnegbin.Rd ├── MCMCnegbinChange.Rd ├── MCMCoprobit.Rd ├── MCMCoprobitChange.Rd ├── MCMCordfactanal.Rd ├── MCMCpaircompare.Rd ├── MCMCpaircompare2d.Rd ├── MCMCpaircompare2dDP.Rd ├── MCMCpoisson.Rd ├── MCMCpoissonChange.Rd ├── MCMCprobit.Rd ├── MCMCprobitChange.Rd ├── MCMCquantreg.Rd ├── MCMCregress.Rd ├── MCMCregressChange.Rd ├── MCMCresidualBreakAnalysis.Rd ├── MCMCtobit.Rd ├── MCbinomialbeta.Rd ├── MCmultinomdirichlet.Rd ├── MCnormalnormal.Rd ├── MCpoissongamma.Rd ├── Nethvote.Rd ├── NoncenHypergeom.Rd ├── PErisk.Rd ├── PostProbMod.Rd ├── Rehnquist.Rd ├── SSVSquantreg.Rd ├── Senate.Rd ├── SupremeCourt.Rd ├── Wishart.Rd ├── choicevar.Rd ├── dtomogplot.Rd ├── make.breaklist.Rd ├── mptable.Rd ├── plot.qrssvs.Rd ├── plotChangepoint.Rd ├── plotHDPChangepoint.Rd ├── plotState.Rd ├── procrustes.Rd ├── read.Scythe.Rd ├── summaryqrssvs.Rd ├── testpanelGroupBreak.Rd ├── testpanelSubjectBreak.Rd ├── tomogplot.Rd ├── topmodels.Rd ├── vech.Rd ├── write.Scythe.Rd └── xpnd.Rd └── src ├── HMMmultivariateGaussian.cc ├── MCMCdynamicEI.cc ├── MCMCfcds.h ├── MCMChierBetaBinom.cc ├── MCMChierEI.cc ├── MCMCirtKdHet.cc ├── MCMCirtKdRob.cc ├── MCMClogituserprior.cc ├── MCMCmetrop1R.cc ├── MCMCmixfactanal.cc ├── MCMCmnl.h ├── MCMCmnlMH.cc ├── MCMCmnlslice.cc ├── MCMCnbutil.cc ├── MCMCnbutil.h ├── MCMCordfactanal.cc ├── MCMCpack_init.c ├── MCMCrng.h ├── Makevars.in ├── Makevars.win ├── algorithm.h ├── cHDPHMMnegbin.cc ├── cHDPHMMpoisson.cc ├── cHDPHSMMnegbin.cc ├── cHMMpanelFE.cc ├── cHMMpanelRE.cc ├── cMCMCSVDreg.cc ├── cMCMCbinaryChange.cc ├── cMCMCdynamicIRT1d-b.cc ├── cMCMCdynamicIRT1d.cc ├── cMCMCfactanal.cc ├── cMCMChlogit.cc ├── cMCMChpoisson.cc ├── cMCMChregress.cc ├── cMCMCirt1d.cc ├── cMCMCirtHier1d.cc ├── cMCMClogit.cc ├── cMCMCnegbin.cc ├── cMCMCnegbinChange.cc ├── cMCMCoprobit.cc ├── cMCMCoprobitChange.cc ├── cMCMCpaircompare.cc ├── cMCMCpaircompare2d.cc ├── cMCMCpaircompare2dDP.cc ├── cMCMCpoisson.cc ├── cMCMCpoissonChange.cc ├── cMCMCprobit.cc ├── cMCMCprobitChange.cc ├── cMCMCprobitres.cc ├── cMCMCquantreg.cc ├── cMCMCregress.cc ├── cMCMCregressChange.cc ├── cMCMCresidualBreakAnalysis.cc ├── cMCMCtobit.cc ├── cSSVSquantreg.cc ├── datablock.h ├── defs.h ├── distributions.h ├── error.h ├── ide.h ├── la.h ├── lapack.h ├── lecuyer.cc ├── lecuyer.h ├── matrix.h ├── matrix_bidirectional_iterator.h ├── matrix_forward_iterator.h ├── matrix_random_access_iterator.h ├── mersenne.h ├── optimize.h ├── rng.h ├── rtmvnorm.h ├── smath.h ├── stat.h └── wrapped_generator.h /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: MCMCpack 2 | Version: 1.7-1 3 | Date: 2024-08-27 4 | Title: Markov Chain Monte Carlo (MCMC) Package 5 | Authors@R: c(person(given = c("Andrew", "D."), 6 | family = "Martin", 7 | role = "aut"), 8 | person(given = c("Kevin", "M."), 9 | family = "Quinn", 10 | role = "aut"), 11 | person(given = c("Jong", "Hee"), 12 | family = "Park", 13 | role = c("aut", "cre"), 14 | email = "jongheepark@snu.ac.kr"), 15 | person(given = "Ghislain", 16 | family = "Vieilledent", 17 | role = "ctb"), 18 | person(given = "Michael", 19 | family = "Malecki", 20 | role = "ctb"), 21 | person(given = "Matthew", 22 | family = "Blackwell", 23 | role = "ctb"), 24 | person(given = "Keith", 25 | family = "Poole", 26 | role = "ctb"), 27 | person(given = "Craig", 28 | family = "Reed", 29 | role = "ctb"), 30 | person(given = "Ben", 31 | family = "Goodrich", 32 | role = "ctb"), 33 | person(given = "Qiushi", 34 | family = "Yu", 35 | role = "ctb"), 36 | person(given = "Ross", 37 | family = "Ihaka", 38 | role = "cph"), 39 | person(given = c("The", "R", "Development", "Core"), 40 | family = "Team", 41 | role = "cph"), 42 | person(given = c("The", "R"), 43 | family = "Foundation", 44 | role = "cph"), 45 | person(given = "Pierre", 46 | family = "L'Ecuyer", 47 | role = "cph"), 48 | person(given = "Makoto", 49 | family = "Matsumoto", 50 | role = "cph"), 51 | person(given = "Takuji", 52 | family = "Nishimura", 53 | role = "cph")) 54 | Depends: R (>= 3.6), coda (>= 0.11-3), MASS, stats 55 | Imports: graphics, grDevices, lattice, methods, utils, mcmc, quantreg 56 | Description: Contains functions to perform Bayesian 57 | inference using posterior simulation for a number of 58 | statistical models. Most simulation is done in compiled C++ 59 | written in the Scythe Statistical Library Version 1.0.3. All 60 | models return 'coda' mcmc objects that can then be summarized 61 | using the 'coda' package. Some useful 62 | utility functions such as density functions, 63 | pseudo-random number generators for statistical 64 | distributions, a general purpose Metropolis sampling algorithm, 65 | and tools for visualization are provided. 66 | License: GPL-3 67 | SystemRequirements: gcc (>= 4.0) 68 | URL: https://CRAN.R-project.org/package=MCMCpack 69 | Packaged: 2024-08-27 05:25:26 UTC; jongheepark 70 | NeedsCompilation: yes 71 | Repository: CRAN 72 | RoxygenNote: 7.3.1 73 | Encoding: UTF-8 74 | Date/Publication: 2024-08-27 06:30:02 UTC 75 | Author: Andrew D. Martin [aut], 76 | Kevin M. Quinn [aut], 77 | Jong Hee Park [aut, cre], 78 | Ghislain Vieilledent [ctb], 79 | Michael Malecki [ctb], 80 | Matthew Blackwell [ctb], 81 | Keith Poole [ctb], 82 | Craig Reed [ctb], 83 | Ben Goodrich [ctb], 84 | Qiushi Yu [ctb], 85 | Ross Ihaka [cph], 86 | The R Development Core Team [cph], 87 | The R Foundation [cph], 88 | Pierre L'Ecuyer [cph], 89 | Makoto Matsumoto [cph], 90 | Takuji Nishimura [cph] 91 | Maintainer: Jong Hee Park 92 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | S3method(plot,qrssvs) 4 | S3method(print,BayesFactor) 5 | S3method(print,qrssvs) 6 | S3method(print,summary.qrssvs) 7 | S3method(summary,BayesFactor) 8 | S3method(summary,qrssvs) 9 | export(BayesFactor) 10 | export(HDPHMMnegbin) 11 | export(HDPHMMpoisson) 12 | export(HDPHSMMnegbin) 13 | export(HMMpanelFE) 14 | export(HMMpanelRE) 15 | export(MCMCSVDreg) 16 | export(MCMCbinaryChange) 17 | export(MCMCdynamicEI) 18 | export(MCMCdynamicIRT1d) 19 | export(MCMCfactanal) 20 | export(MCMChierEI) 21 | export(MCMChlogit) 22 | export(MCMChpoisson) 23 | export(MCMChregress) 24 | export(MCMCirt1d) 25 | export(MCMCirtHier1d) 26 | export(MCMCirtKd) 27 | export(MCMCirtKdRob) 28 | export(MCMClogit) 29 | export(MCMCmetrop1R) 30 | export(MCMCmixfactanal) 31 | export(MCMCmnl) 32 | export(MCMCnegbin) 33 | export(MCMCnegbinChange) 34 | export(MCMCoprobit) 35 | export(MCMCoprobitChange) 36 | export(MCMCordfactanal) 37 | export(MCMCpaircompare) 38 | export(MCMCpaircompare2d) 39 | export(MCMCpaircompare2dDP) 40 | export(MCMCpoisson) 41 | export(MCMCpoissonChange) 42 | export(MCMCprobit) 43 | export(MCMCprobitChange) 44 | export(MCMCquantreg) 45 | export(MCMCregress) 46 | export(MCMCregressChange) 47 | export(MCMCresidualBreakAnalysis) 48 | export(MCMCtobit) 49 | export(MCbinomialbeta) 50 | export(MCmultinomdirichlet) 51 | export(MCnormalnormal) 52 | export(MCpoissongamma) 53 | export(PostProbMod) 54 | export(SSVSquantreg) 55 | export(choicevar) 56 | export(ddirichlet) 57 | export(dinvgamma) 58 | export(diwish) 59 | export(dnoncenhypergeom) 60 | export(dtomogplot) 61 | export(dwish) 62 | export(is.BayesFactor) 63 | export(make.breaklist) 64 | export(mptable) 65 | export(plotChangepoint) 66 | export(plotHDPChangepoint) 67 | export(plotState) 68 | export(procrustes) 69 | export(rdirichlet) 70 | export(read.Scythe) 71 | export(rinvgamma) 72 | export(riwish) 73 | export(rnoncenhypergeom) 74 | export(rwish) 75 | export(testpanelGroupBreak) 76 | export(testpanelSubjectBreak) 77 | export(tomogplot) 78 | export(topmodels) 79 | export(vech) 80 | export(write.Scythe) 81 | export(xpnd) 82 | import(MASS) 83 | import(coda) 84 | import(grDevices) 85 | import(lattice) 86 | import(mcmc) 87 | import(methods) 88 | import(quantreg) 89 | import(stats) 90 | import(utils) 91 | importFrom(graphics,abline) 92 | importFrom(graphics,axTicks) 93 | importFrom(graphics,axis) 94 | importFrom(graphics,box) 95 | importFrom(graphics,layout) 96 | importFrom(graphics,lcm) 97 | importFrom(graphics,legend) 98 | importFrom(graphics,lines) 99 | importFrom(graphics,par) 100 | importFrom(graphics,plot) 101 | importFrom(graphics,plot.new) 102 | importFrom(graphics,plot.window) 103 | importFrom(graphics,points) 104 | importFrom(graphics,rect) 105 | useDynLib(MCMCpack, .registration=TRUE) 106 | -------------------------------------------------------------------------------- /R/MCMChierBetaBinom.R: -------------------------------------------------------------------------------- 1 | ########################################################################### 2 | ## sample from the posterior distribution of a hierarchical beta binomial 3 | ## model in R using linked C++ code in Scythe 4 | ## 5 | ## y_{ij} ~ Binomial(s_{ij}, theta_{ij}) 6 | ## theta_{ij} ~ Beta(alpha_j, beta_j) 7 | ## alpha_j ~ Pareto(1, a) 8 | ## beta_j ~ Pareto(1, b) 9 | ## 10 | ## KQ 5/24/2011 - 6/25/2011 11 | ## 12 | ## This software is distributed under the terms of the GNU GENERAL 13 | ## PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 14 | ## file for more information. 15 | ## 16 | ## 17 | ## Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 18 | ## Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 19 | ## and Jong Hee Park 20 | ########################################################################## 21 | 22 | 23 | "MCMChierBetaBinom" <- function(y, s, i.labels, j.labels, burnin=1000, 24 | mcmc=10000, thin=1, 25 | verbose=0, seed=NA, theta.start=NA, 26 | alpha.start=NA, beta.start=NA, 27 | a=0, b=0){ 28 | 29 | ## checks 30 | check.mcmc.parameters(burnin, mcmc, thin) 31 | max.length <- max(length(y), length(s), length(i.labels), length(j.labels)) 32 | min.length <- min(length(y), length(s), length(i.labels), length(j.labels)) 33 | if (max.length != min.length){ 34 | stop("y, s, i.labels, j.labels not all of same length\n") 35 | } 36 | 37 | na.indic <- is.na(y) 38 | na.indic <- na.indic + is.na(s) 39 | na.indic <- na.indic + is.na(i.labels) 40 | na.indic <- na.indic + is.na(j.labels) 41 | na.indic <- na.indic != 0 42 | y <- y[!na.indic] 43 | s <- s[!na.indic] 44 | i.labels <- i.labels[!na.indic] 45 | j.labels <- j.labels[!na.indic] 46 | 47 | if (min(y) < 0){ 48 | stop("y cannot have an element less than 0\n") 49 | } 50 | if (max(y > s) > 0){ 51 | stop("y[i] cannot be greater than s[i] for any i\n") 52 | } 53 | 54 | ## more checking needed 55 | 56 | 57 | ## seeds 58 | seeds <- form.seeds(seed) 59 | lecuyer <- seeds[[1]] 60 | seed.array <- seeds[[2]] 61 | lecuyer.stream <- seeds[[3]] 62 | 63 | 64 | 65 | i.labels <- as.character(i.labels) 66 | j.labels <- as.character(j.labels) 67 | i.labels.unique <- unique(i.labels) 68 | j.labels.unique <- unique(j.labels) 69 | i.labels.num <- rep(NA, length(i.labels)) 70 | j.labels.num <- rep(NA, length(j.labels)) 71 | for (i in 1:length(i.labels)){ 72 | i.labels.num[i] <- which(i.labels.unique == i.labels[i]) 73 | } 74 | for (j in 1:length(j.labels)){ 75 | j.labels.num[j] <- which(j.labels.unique == j.labels[j]) 76 | } 77 | i.labels.num.unique <- unique(i.labels.num) 78 | j.labels.num.unique <- unique(j.labels.num) 79 | 80 | 81 | 82 | ## starting values 83 | if (length(theta.start) == 1){ 84 | if (is.numeric(theta.start)){ 85 | theta.start <- rep(theta.start, length(y)) 86 | } 87 | else if (is.na(theta.start)){ 88 | theta.start <- (y + 0.01) / (s + 0.02) 89 | } 90 | else{ 91 | theta.start <- rep(0.5, length(y)) 92 | } 93 | } 94 | if (length(theta.start) != length(y)){ 95 | stop("length(theta.start) != length(y)\n") 96 | } 97 | if (max(theta.start) >= 1.0){ 98 | stop("elements of theta.start must be less than 1.0\n") 99 | } 100 | if (min(theta.start) <= 0.0){ 101 | stop("elements of theta.start must be greater than 0.0\n") 102 | } 103 | 104 | if (length(alpha.start) == 1){ 105 | if (is.na(alpha.start)){ 106 | alpha.start <- rep(1.001, length(j.labels.unique)) 107 | } 108 | } 109 | if (length(alpha.start) != length(j.labels.unique)){ 110 | stop("length(alpha.start) != length(unique(j.labels))\n") 111 | } 112 | if (length(beta.start) == 1){ 113 | if (is.na(beta.start)){ 114 | beta.start <- rep(1.001, length(j.labels.unique)) 115 | } 116 | } 117 | if (length(beta.start) != length(j.labels.unique)){ 118 | stop("length(beta.start) != length(unique(j.labels))\n") 119 | } 120 | 121 | 122 | accepts <- rep(0, length(j.labels.unique)) 123 | 124 | 125 | 126 | 127 | 128 | ## get reasonable values for base.sigma 129 | base.sigma <- rep(1, length(j.labels.unique)) 130 | 131 | 132 | 133 | ## call C++ code to draw the sample 134 | sample <- matrix(data=0, mcmc/thin, (length(y) + 135 | 2*length(j.labels.unique)) ) 136 | 137 | 138 | posterior <- .C("hierBetaBinom", 139 | samdata = as.double(sample), 140 | samrow = as.integer(nrow(sample)), 141 | samcol = as.integer(ncol(sample)), 142 | y = as.integer(y), 143 | s = as.integer(s), 144 | theta = as.double(theta.start), 145 | alpha = as.double(alpha.start), 146 | beta = as.double(beta.start), 147 | a = as.double(a), 148 | b = as.double(b), 149 | ilabels = as.integer(i.labels.num), 150 | jlabels = as.integer(j.labels.num), 151 | ilabelsunique = as.integer(i.labels.num.unique), 152 | jlabelsunique = as.integer(j.labels.num.unique), 153 | n = as.integer(length(y)), 154 | ni = as.integer(length(i.labels.unique)), 155 | nj = as.integer(length(j.labels.unique)), 156 | burnin = as.integer(burnin), 157 | mcmc = as.integer(mcmc), 158 | thin = as.integer(thin), 159 | lecuyer = as.integer(lecuyer), 160 | seedarray = as.integer(seed.array), 161 | lecuyerstream = as.integer(lecuyer.stream), 162 | verbose = as.integer(verbose), 163 | accepts = as.integer(accepts), 164 | basesigma = as.double(base.sigma), 165 | PACKAGE="MCMCpack") 166 | 167 | 168 | sample <- matrix(posterior$samdata, 169 | posterior$samrow, 170 | posterior$samcol, 171 | byrow=FALSE) 172 | 173 | output <- mcmc(data=sample, start=burnin+1, end=burnin+mcmc, thin=thin) 174 | 175 | theta.names <- paste("theta.", i.labels, ".", j.labels, sep="") 176 | alpha.names <- paste("alpha.", j.labels.unique, sep="") 177 | beta.names <- paste("beta.", j.labels.unique, sep="") 178 | 179 | varnames(output) <- c(theta.names, alpha.names, beta.names) 180 | 181 | attr(output, "title") <- "MCMChierBetaBinom Posterior Sample" 182 | attr(output, "acceptance.rates") <- posterior$accepts / (posterior$mcmc + posterior$burnin) 183 | return(output) 184 | 185 | 186 | } ## end MCMChierBetaBinom 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | -------------------------------------------------------------------------------- /R/MCMCpack-package.R: -------------------------------------------------------------------------------- 1 | #' @useDynLib MCMCpack, .registration=TRUE 2 | #' @import coda 3 | #' @import MASS 4 | #' @import stats 5 | #' @import utils 6 | #' @import grDevices 7 | #' @import lattice 8 | #' @import methods 9 | #' @import mcmc 10 | #' @import quantreg 11 | #' @importFrom graphics plot lines abline axTicks axis box layout lcm legend par plot.new plot.window points rect 12 | NULL 13 | #> NULL 14 | -------------------------------------------------------------------------------- /R/hdp-utils.R: -------------------------------------------------------------------------------- 1 | #' Posterior Changepoint Probabilities from HDP-HMM 2 | #' 3 | #' Plot the posterior density of regime change. 4 | #' 5 | #' @param mcmcout The \code{mcmc} object containing the posterior density 6 | #' sample from a changepoint model. Note that this must be from a 7 | #' HDP-HMM sampler. 8 | #' 9 | #' @param main Title of the plot 10 | #' 11 | #' @param xlab Label for the x-axis. 12 | #' 13 | #' @param ylab Label for the y-axis. 14 | #' 15 | #' @param start The time of the first observation to be shown in the time 16 | #' series plot. 17 | #' 18 | #' @export 19 | #' 20 | #' @seealso \code{\link{HDPHMMpoisson}}, \code{\link{HDPHMMnegbin}}, \code{\link{HDPHSMMnegbin}} 21 | #' 22 | #' @keywords hplot 23 | "plotHDPChangepoint" <- 24 | function (mcmcout, main="Posterior Changepoint Probabilities", xlab = "Time", ylab = "", 25 | start = 1){ 26 | pr.st <- attr(mcmcout, "pr.chpt") 27 | y <- attr(mcmcout, "y") 28 | K <- attr(mcmcout, "K") 29 | if (!is.ts(y)) 30 | y <- ts(y, start) 31 | time.frame <- as.vector(time(y)) 32 | stopifnot(K > 1) 33 | plot(time.frame, pr.st, type = "h", lwd=2, main = main, ylim=c(0, max(pr.st)), xlab = xlab, ylab = ylab, axes=FALSE) 34 | axis(1, tick = FALSE, col="darkgrey", lwd=0.5) 35 | axis(2, tick = FALSE, col="darkgrey", lwd=0.5) 36 | for (i in 1:length(axTicks(1))) lines(c(axTicks(1)[i], axTicks(1)[i]), c(0,1), col="darkgrey", lwd=0.5) 37 | for (i in 1:length(axTicks(2))) lines(c(axTicks(2)[1], max(time.frame)), 38 | c(axTicks(2)[i], axTicks(2)[i]), col="darkgrey", lwd=0.5) 39 | invisible() 40 | } 41 | 42 | ## prior check for transition matrix 43 | "check.hdp.P" <- function(P.start = NA, K = K, n = n, theta = theta){ 44 | if (is.na(P.start)[1]){ 45 | P <- matrix((1 - theta) / (K - 1), nrow = K, ncol = K) 46 | diag(P) <- theta 47 | } else if ((dim(P.start)[1] == K)&(dim(P.start)[2] == K)){ 48 | if ((max(P.start) > 1) || (min(P.start) < 0)) { 49 | stop("Error: P starting values are out of unit range.\n") 50 | } 51 | else 52 | P <- P.start 53 | } 54 | else { 55 | stop("Error: P starting values are not conformable.\n") 56 | } 57 | return(P) 58 | } 59 | -------------------------------------------------------------------------------- /R/make.breaklist.R: -------------------------------------------------------------------------------- 1 | #' Vector of break numbers 2 | #' 3 | #' This function generates a vector of break numbers using the output of 4 | #' \code{testpanelSubjectBreak}. The function performs a pairwise comparison 5 | #' of models using Bayes Factors. 6 | #' 7 | #' @param BF output of \code{testpanelSubjectBreak}. 8 | #' 9 | #' @param threshold The Bayes Factor threshold to pick the best model. If a 10 | #' Bayes factor of two models is smaller than \code{threshold}, the model with 11 | #' a smaller number of break is chosen to avoid the over-identification 12 | #' problem. Users can change threshold into any positive number. The default 13 | #' value of 3 is chosen as it indicates the existence of "substantial evidence" 14 | #' in favor of the model in the numerator according to Jeffreys' scale. 15 | #' 16 | #' @return Vector fo break numbers. 17 | #' 18 | #' @export 19 | #' 20 | #' @seealso \code{\link{testpanelSubjectBreak}} 21 | #' 22 | #' @references Jong Hee Park, 2012. ``Unified Method for Dynamic and 23 | #' Cross-Sectional Heterogeneity: Introducing Hidden Markov Panel 24 | #' Models.'' \emph{American Journal of Political Science}.56: 25 | #' 1040-1054. 26 | #' 27 | #' Harold Jeffreys, 1961. The Theory of Probability. Oxford University Press. 28 | "make.breaklist" <- function(BF, threshold=3){ 29 | eBF <- exp(BF) 30 | N <- nrow(BF) 31 | out <- rep(NA, N) 32 | for (i in 1:N){ 33 | order.i <- order(eBF[i,], decreasing=TRUE) 34 | if(sum(is.na(eBF[i,]))>0){ 35 | out[i] <- 1 36 | } 37 | else{ 38 | if(eBF[i, order.i[1]] / eBF[i, order.i[2]] > threshold){ 39 | out[i] <- order.i[1] 40 | } 41 | else if (eBF[i, order.i[1]] / eBF[i, order.i[2]] < threshold & order.i[1]<=order.i[2]){ 42 | out[i] <- order.i[1] 43 | } 44 | else if (eBF[i, order.i[1]] / eBF[i, order.i[2]] < threshold & order.i[1]>order.i[2]){ 45 | out[i] <- order.i[2] 46 | } 47 | else{ 48 | cat("\n Error occurs at i = ", i) 49 | } 50 | } 51 | } 52 | return(out-1) 53 | } 54 | -------------------------------------------------------------------------------- /R/procrust.R: -------------------------------------------------------------------------------- 1 | ########################################################################## 2 | ## function that performs procrustes transformation on X with target Xstar 3 | ## 4 | ## returns the rotation matrix R, translation vector tt, 5 | ## and dilation factor s for which: 6 | ## 7 | ## s X R + 1 tt' \approx Xstar 8 | ## 9 | ## along with X.new = s X R + 1 tt' 10 | ## 11 | ## Based on Borg and Groenen 1997. Modern Multidimensional 12 | ## Scaling. New York: Springer. pp. 340-342. 13 | ## 14 | ## This software is distributed under the terms of the GNU GENERAL 15 | ## PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 16 | ## file for more information. 17 | ## 18 | ## Kevin Quinn 19 | ## Harvard University 20 | ## 6/13/2005 21 | ## 22 | ## Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 23 | ## Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 24 | ## and Jong Hee Park 25 | ########################################################################## 26 | 27 | 28 | #' Procrustes Transformation 29 | #' 30 | #' This function performs a Procrustes transformation on a matrix \code{X} to 31 | #' minimize the squared distance between \code{X} and another matrix 32 | #' \code{Xstar}. 33 | #' 34 | #' \code{R}, \code{tt}, and \code{s} are chosen so that: 35 | #' 36 | #' \deqn{s X R + 1 tt' \approx X^*} 37 | #' 38 | #' \code{X.new} is given by: 39 | #' 40 | #' \deqn{X_{new} = s X R + 1 tt'} 41 | #' 42 | #' @param X The matrix to be transformed. 43 | #' 44 | #' @param Xstar The target matrix. 45 | #' 46 | #' @param translation logical value indicating whether \code{X} should be 47 | #' translated. 48 | #' 49 | #' @param dilation logical value indicating whether \code{X} should be dilated. 50 | #' 51 | #' @return A list containing: \code{X.new} the matrix that is the Procrustes 52 | #' transformed version of \code{X}, \code{R} the rotation matrix, \code{tt} the 53 | #' translation vector, and \code{s} the scale factor. 54 | #' 55 | #' @export 56 | #' 57 | #' @seealso \code{\link{MCMCirtKd}} 58 | #' 59 | #' @references Borg and Groenen. 1997. \emph{Modern Multidimensional Scaling}. 60 | #' New York: Springer. pp. 340-342. 61 | #' 62 | #' @keywords manip 63 | procrustes <- function(X, Xstar, translation=FALSE, dilation=FALSE){ 64 | if (nrow(X) != nrow(Xstar)){ 65 | cat("X and Xstar do not have same number of rows.\n") 66 | stop("Check data and call procrustes() again. \n") 67 | } 68 | if (ncol(X) != ncol(Xstar)){ 69 | cat("X and Xstar do not have same number of columns.\n") 70 | stop("Check data and call procrustes() again. \n") 71 | } 72 | 73 | n <- nrow(X) 74 | m <- ncol(X) 75 | 76 | if (translation){ 77 | J <- diag(n) - 1/n * matrix(1, n, n) 78 | } 79 | else{ 80 | J <- diag(n) 81 | } 82 | 83 | C <- t(Xstar) %*% J %*% X 84 | svd.out <- svd(C) 85 | R <- svd.out$v %*% t(svd.out$u) 86 | s <- 1 87 | if (dilation){ 88 | mat1 <- t(Xstar) %*% J %*% X %*% R 89 | mat2 <- t(X) %*% J %*% X 90 | s.numer <- 0 91 | s.denom <- 0 92 | for (i in 1:m){ 93 | s.numer <- s.numer + mat1[i,i] 94 | s.denom <- s.denom + mat2[i,i] 95 | } 96 | s <- s.numer / s.denom 97 | } 98 | tt <- matrix(0, m, 1) 99 | if (translation){ 100 | tt <- 1/n * t(Xstar - s*X %*% R) %*% matrix(1, n, 1) 101 | } 102 | 103 | X.new <- s * X %*% R + matrix(tt, nrow(X), ncol(X), byrow=TRUE) 104 | 105 | return(list(X.new=X.new, R=R, tt=tt, s=s)) 106 | } 107 | -------------------------------------------------------------------------------- /R/scythe.R: -------------------------------------------------------------------------------- 1 | ########################################################################## 2 | ## Scythe Inter-Operation Functions 3 | ## 4 | ## This software is distributed under the terms of the GNU GENERAL 5 | ## PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 6 | ## file for more information. 7 | ## 8 | ## Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 9 | ## Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 10 | ## and Jong Hee Park 11 | ########################################################################## 12 | 13 | 14 | # writes a matrix out to an ASCII file that can be read by Scythe. 15 | # it puts the number of rows and columns in the first row 16 | # followed by the data. 17 | # 18 | # ADM 1/29/2003 19 | 20 | #' Write a Matrix to a File to be Read by Scythe 21 | #' 22 | #' This function writes a matrix to an ASCII file that can be read by the 23 | #' Sycthe Statistical Library. Scythe requires that input files contain the 24 | #' number of rows and columns in the first row, followed by the data. 25 | #' 26 | #' @param outmatrix The matrix to be written to a file. 27 | #' 28 | #' @param outfile The file to be written. This can include path information. 29 | #' 30 | #' @param overwrite A logical that determines whether an existing file should 31 | #' be over-written. By default, it protects the user from over-writing 32 | #' existing files. 33 | #' 34 | #' @return A zero if the file is properly written. 35 | #' 36 | #' @export 37 | #' 38 | #' @seealso \code{\link{write.Scythe}} 39 | #' 40 | #' @references Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 41 | #' \emph{Scythe Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 42 | #' 43 | #' @keywords file 44 | #' 45 | #' @examples 46 | #' 47 | #' \dontrun{ 48 | #' write.Scythe(mymatrix, file.path(tempdir(), "myfile.txt")) 49 | #' } 50 | #' 51 | "write.Scythe" <- 52 | function(outmatrix, outfile = NA, overwrite=FALSE) { 53 | outmatrix <- as.matrix(outmatrix) 54 | 55 | if(is.na(outfile)) { 56 | stop("Please specify a file name in the write.Scythe() call.\n") 57 | } 58 | if(overwrite==FALSE & file.exists(outfile)) { 59 | cat("File already exists in the write.Scythe() call.\n") 60 | stop("Either delete the file, or flip the overwrite switch.\n") 61 | } 62 | 63 | outfile <- file(outfile, "w") 64 | cat(dim(outmatrix), "\n", file=outfile) 65 | write.table(outmatrix, file=outfile, 66 | row.names=FALSE, col.names=FALSE, quote=FALSE) 67 | close(outfile) 68 | return(0) 69 | } 70 | 71 | 72 | # reads in a matrix from an ASCII file written by Scythe. 73 | # the number of rows and columns should be in the first row followed 74 | # by the data. 75 | # 76 | # Kevin Rompala 5/1/2003 77 | # fixed by ADM 7/25/2004 78 | 79 | #' Read a Matrix from a File written by Scythe 80 | #' 81 | #' This function reads a matrix from an ASCII file in the form produced by the 82 | #' Scythe Statistical Library. Scythe output files contain the number of rows 83 | #' and columns in the first row, followed by the data. 84 | #' 85 | #' 86 | #' @param infile The file to be read. This can include path information. 87 | #' 88 | #' @return A matrix containing the data stored in the read file. 89 | #' 90 | #' @export 91 | #' 92 | #' @seealso \code{\link{write.Scythe}} 93 | #' 94 | #' @references Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 95 | #' \emph{Scythe Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 96 | #' 97 | #' @keywords file 98 | #' 99 | #' @examples 100 | #' 101 | #' \dontrun{ 102 | #' mymatrix <- read.Scythe("myfile.txt") 103 | #' } 104 | #' 105 | "read.Scythe" <- 106 | function(infile = NA) { 107 | 108 | if(is.na(infile)) { 109 | stop("Please specify a file name in the read.Scythe() call.\n") 110 | } 111 | if(!file.exists(infile)) { 112 | stop("Specified source file does not exist in read.Scythe() call.\n") 113 | } 114 | 115 | infile <- file(infile, "r") 116 | dimensions <- scan(file=infile,n=2) 117 | inputdata <- scan(file=infile) 118 | close(infile) 119 | hold <- matrix(data=inputdata, 120 | nrow=dimensions[1], ncol=dimensions[2], byrow=TRUE) 121 | return(hold) 122 | } 123 | -------------------------------------------------------------------------------- /R/utility.R: -------------------------------------------------------------------------------- 1 | ########################################################################## 2 | ## Utility Functions 3 | ## 4 | ## This software is distributed under the terms of the GNU GENERAL 5 | ## PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 6 | ## file for more information. 7 | ## 8 | ## Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 9 | ## Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 10 | ## and Jong Hee Park 11 | ########################################################################## 12 | 13 | 14 | # takes a symmetric matrix x and returns lower diagonal 15 | # note: does not check for symmetry 16 | # 17 | # ADM 4/18/2003 18 | 19 | #' Extract Lower Triangular Elements from a Symmetric Matrix 20 | #' 21 | #' This function takes a symmetric matrix and extracts a list of all lower 22 | #' triangular elements. 23 | #' 24 | #' This function checks to make sure the matrix is square, but it does not 25 | #' check for symmetry (it just pulls the lower triangular elements). The 26 | #' elements are stored in column major order. The original matrix can be 27 | #' restored using the \code{xpnd} command. 28 | #' 29 | #' @param x A symmetric matrix. 30 | #' 31 | #' @return A list of the lower triangular elements. 32 | #' 33 | #' @export 34 | #' 35 | #' @seealso \code{\link{xpnd}} 36 | #' 37 | #' @keywords manip 38 | #' 39 | #' @examples 40 | #' 41 | #' symmat <- matrix(c(1,2,3,4,2,4,5,6,3,5,7,8,4,6,8,9),4,4) 42 | #' vech(symmat) 43 | #' 44 | "vech" <- 45 | function (x) { 46 | x <- as.matrix(x) 47 | if (dim(x)[1] != dim(x)[2]) { 48 | stop("Non-square matrix passed to vech().\n") 49 | } 50 | output <- x[lower.tri(x, diag = TRUE)] 51 | dim(output) <- NULL 52 | return(output) 53 | } 54 | 55 | # takes vector x and returns an nrow times nrow symmetric matrix 56 | # this will recycle the elements of x as needed to fill the matrix 57 | # 58 | # ADM 4/18/2003 59 | # ADM 11/13/2003 [bug fix] 60 | # ADM 1/25/2006 [patch to automatically compute matrix size] 61 | 62 | #' Expand a Vector into a Symmetric Matrix 63 | #' 64 | #' This function takes a vector of appropriate length (typically created using 65 | #' \code{vech}) and creates a symmetric matrix. 66 | #' 67 | #' This function is particularly useful when dealing with variance covariance 68 | #' matrices. Note that R stores matrices in column major order, and that the 69 | #' items in \code{x} will be recycled to fill the matrix if need be. 70 | #' 71 | #' The number of rows can be specified or automatically computed from the 72 | #' number of elements in a given object via \eqn{(-1 + \sqrt{(1 + 8 * 73 | #' length(x))}) / 2}. 74 | #' 75 | #' @param x A list of elements to expand into symmetric matrix. 76 | #' 77 | #' @param nrow The number of rows (and columns) in the returned matrix. Look 78 | #' into the details. 79 | #' 80 | #' @export 81 | #' 82 | #' @return An \eqn{(nrows \times nrows)} symmetric matrix. 83 | #' 84 | #' @seealso \code{\link{vech}} 85 | #' 86 | #' @keywords manip 87 | #' 88 | #' @examples 89 | #' 90 | #' xpnd(c(1,2,3,4,4,5,6,7,8,9),4) 91 | #' xpnd(c(1,2,3,4,4,5,6,7,8,9)) 92 | #' 93 | "xpnd" <- 94 | function (x, nrow = NULL) { 95 | dim(x) <- NULL 96 | if(is.null(nrow)) nrow <- (-1 + sqrt(1 + 8 * length(x))) / 2 97 | output <- matrix(0, nrow, nrow) 98 | output[lower.tri(output, diag = TRUE)] <- x 99 | hold <- output 100 | hold[upper.tri(hold, diag=TRUE)] <- 0 101 | output <- output + t(hold) 102 | return(output) 103 | } 104 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | ########################################################################## 2 | ## start-up and clean-up functions 3 | ## 4 | ## This software is distributed under the terms of the GNU GENERAL 5 | ## PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 6 | ## file for more information. 7 | ## 8 | ## Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 9 | ## Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 10 | ## and Jong Hee Park 11 | ########################################################################## 12 | 13 | .onAttach <- function(...) { 14 | 15 | # figure out year automatically (probably could be done more elegantly) 16 | date <- date() 17 | x <- regexpr("[0-9]{4}", date) 18 | this.year <- substr(date, x[1], x[1] + attr(x, "match.length") - 1) 19 | 20 | # echo output to screen 21 | packageStartupMessage("##\n## Markov Chain Monte Carlo Package (MCMCpack)") 22 | packageStartupMessage("## Copyright (C) 2003-", this.year, 23 | " Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park", sep="") 24 | packageStartupMessage("##\n## Support provided by the U.S. National Science Foundation") 25 | packageStartupMessage("## (Grants SES-0350646 and SES-0350613)\n##") 26 | ## require(coda, quietly=TRUE) 27 | ## require(MASS, quietly=TRUE) 28 | ## require(stats, quietly=TRUE) 29 | } 30 | 31 | .onUnload <- function(libpath) { 32 | library.dynam.unload("MCMCpack", libpath) 33 | } 34 | 35 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | ///////////////////// 2 | // MCMCpack README // 3 | ///////////////////// 4 | 5 | // Authors 6 | 7 | Andrew D. Martin 8 | Kevin M. Quinn 9 | Jong Hee Park 10 | 11 | // Compilation 12 | 13 | This package (along with Scythe) uses C++ and the Standard Template 14 | Library (STL). We suggest using of the GCC compiler 4.0 or greater. The 15 | current package has been tested using GCC 4.0 on Linux and MacOS X. 16 | 17 | Many thanks to Dan Pemstein for helping with all sorts of C++ issues, 18 | and to Kurt Hornik and Fritz Leisch for their help with debugging as 19 | well as their service to the R community. We are also very grateful to 20 | Brian Ripley who provided C++ patches to fix a number of clang and Solaris 21 | issues. 22 | 23 | // Acknowledgments 24 | 25 | We gratefully acknowledge support from: 26 | 27 | * National Science Foundation, Program in Methodology, Measurement, and 28 | Statistics, Grants SES-0350646 and SES-0350613 29 | 30 | * Washington University, Department of Political Science, the 31 | Weidenbaum Center on the Economy, Government, and Public Policy 32 | (http://wc.wustl.edu), and the Center for Empirical Research in the Law 33 | (http://cerl.wustl.edu) 34 | 35 | * Harvard University, Department of Government and the 36 | Institute for Quantitative Social Sciences (http://iq.harvard.edu) 37 | 38 | Neither the National Science Foundation, Washington University, or 39 | Harvard University bear any responsibility for the content of this 40 | package. 41 | 42 | Please contact Jong Hee Park if 43 | you have any problems or questions. 44 | 45 | -- 46 | Jong Hee Park, Ph.D. 47 | Professor in Dept. Political Science and International Relations 48 | Seoul National University 49 | 50 | Email: jongheepark@snu.ac.kr 51 | WWW: http://jhp.snu.ac.kr 52 | 53 | -------------------------------------------------------------------------------- /build/partial.rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/build/partial.rdb -------------------------------------------------------------------------------- /cleanup: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | rm -f config.log src/Makevars 3 | 4 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_PREREQ(2.50) 2 | AC_INIT([DESCRIPTION]) 3 | 4 | : ${R_HOME=`R RHOME`} 5 | if test -z "${R_HOME}"; then 6 | echo "could not determine R_HOME" 7 | exit 1 8 | fi 9 | CXX=`${R_HOME}/bin/R CMD config CXX` 10 | 11 | AC_PROG_CXX 12 | 13 | if test "${GXX}" = yes; then 14 | gxx_version=`${CXX} -v 2>&1 | grep "^.*g.. version" | \ 15 | sed -e 's/^.*g.. version *//'` 16 | case ${gxx_version} in 17 | 1.*|2.*|3.*) 18 | AC_MSG_WARN([Only g++ version 4.0 or greater can be used with MCMCpack.]) 19 | AC_MSG_ERROR([Please use a different compiler.]) 20 | ;; 21 | esac 22 | fi 23 | 24 | AC_CHECK_HEADERS(ieeefp.h, [MV_HAVE_IEEEFP_H="-DHAVE_IEEEFP_H"], [MV_HAVE_IEEFP_H=""]) 25 | AC_CHECK_FUNCS(trunc, [MV_HAVE_TRUNC="-DHAVE_TRUNC"], [MV_HAVE_TRUNC=""]) 26 | AC_SUBST(MV_HAVE_IEEEFP_H) 27 | AC_SUBST(MV_HAVE_TRUNC) 28 | AC_CONFIG_FILES([src/Makevars]) 29 | AC_OUTPUT 30 | -------------------------------------------------------------------------------- /data/Euro2016.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/Euro2016.rda -------------------------------------------------------------------------------- /data/Nethvote.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/Nethvote.rda -------------------------------------------------------------------------------- /data/PErisk.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/PErisk.rda -------------------------------------------------------------------------------- /data/Rehnquist.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/Rehnquist.rda -------------------------------------------------------------------------------- /data/Senate.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/Senate.rda -------------------------------------------------------------------------------- /data/SupremeCourt.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/MCMCpack/2b02c1d57d83f372fa6b3bc5522e27701690d0d9/data/SupremeCourt.rda -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | bibentry( 2 | bibtype = "Article", 3 | title = "{MCMCpack}: Markov Chain Monte Carlo in {R}", 4 | author = c( 5 | person(c("Andrew", "D."), "Martin", role = "aut"), 6 | person(c("Kevin", "M."), "Quinn", role = "aut"), 7 | person(c("Jong Hee"), "Park", role = c("aut", "cre"), 8 | email = "jongheepark@snu.ac.kr") 9 | ), 10 | year = "2011", 11 | journal = "Journal of Statistical Software", 12 | year = "2011", 13 | volume = {42}, 14 | number = {9}, 15 | pages = {1--21}, 16 | Doi = {"10.18637/jss.v042.i09"} 17 | ) -------------------------------------------------------------------------------- /man/BayesFactor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/BayesFactors.R 3 | \name{BayesFactor} 4 | \alias{BayesFactor} 5 | \alias{is.BayesFactor} 6 | \title{Create an object of class BayesFactor from MCMCpack output} 7 | \usage{ 8 | BayesFactor(...) 9 | 10 | is.BayesFactor(BF) 11 | } 12 | \arguments{ 13 | \item{...}{MCMCpack output objects. These have to be of class 14 | \code{mcmc} and have a \code{logmarglike} attribute. In what 15 | follows, we let \code{M} denote the total number of models to be 16 | compared.} 17 | 18 | \item{BF}{An object to be checked for membership in class 19 | 20 | \code{BayesFactor}.} 21 | } 22 | \value{ 23 | An object of class \code{BayesFactor}. A \code{BayesFactor} 24 | object has four attributes. They are: \code{BF.mat} an \eqn{M 25 | \times M} matrix in which element \eqn{i,j} contains the Bayes 26 | factor for model \eqn{i} relative to model \eqn{j}; 27 | \code{BF.log.mat} an \eqn{M \times M} matrix in which element 28 | \eqn{i,j} contains the natural log of the Bayes factor for model 29 | \eqn{i} relative to model \eqn{j}; \code{BF.logmarglike} an 30 | \eqn{M} vector containing the log marginal likelihoods for models 31 | 1 through \eqn{M}; and \code{BF.call} an \eqn{M} element list 32 | containing the calls used to fit models 1 through \eqn{M}. 33 | } 34 | \description{ 35 | This function creates an object of class \code{BayesFactor} from 36 | MCMCpack output. 37 | } 38 | \examples{ 39 | 40 | \dontrun{ 41 | data(birthwt) 42 | 43 | model1 <- MCMCregress(bwt~age+lwt+as.factor(race) + smoke + ht, 44 | data=birthwt, b0=c(2700, 0, 0, -500, -500, 45 | -500, -500), 46 | B0=c(1e-6, .01, .01, 1.6e-5, 1.6e-5, 1.6e-5, 47 | 1.6e-5), c0=10, d0=4500000, 48 | marginal.likelihood="Chib95", mcmc=10000) 49 | 50 | model2 <- MCMCregress(bwt~age+lwt+as.factor(race) + smoke, 51 | data=birthwt, b0=c(2700, 0, 0, -500, -500, 52 | -500), 53 | B0=c(1e-6, .01, .01, 1.6e-5, 1.6e-5, 1.6e-5), 54 | c0=10, d0=4500000, 55 | marginal.likelihood="Chib95", mcmc=10000) 56 | 57 | model3 <- MCMCregress(bwt~as.factor(race) + smoke + ht, 58 | data=birthwt, b0=c(2700, -500, -500, 59 | -500, -500), 60 | B0=c(1e-6, 1.6e-5, 1.6e-5, 1.6e-5, 61 | 1.6e-5), c0=10, d0=4500000, 62 | marginal.likelihood="Chib95", mcmc=10000) 63 | 64 | BF <- BayesFactor(model1, model2, model3) 65 | print(BF) 66 | 67 | } 68 | 69 | } 70 | \seealso{ 71 | \code{\link{MCMCregress}} 72 | } 73 | \keyword{models} 74 | -------------------------------------------------------------------------------- /man/Dirichlet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/distn.R 3 | \name{Dirichlet} 4 | \alias{Dirichlet} 5 | \alias{ddirichlet} 6 | \alias{rdirichlet} 7 | \title{The Dirichlet Distribution} 8 | \usage{ 9 | ddirichlet(x, alpha) 10 | 11 | rdirichlet(n, alpha) 12 | } 13 | \arguments{ 14 | \item{x}{A vector containing a single deviate or matrix containing one 15 | random deviate per row.} 16 | 17 | \item{alpha}{Vector of shape parameters, or matrix of shape parameters 18 | corresponding to the number of draw.} 19 | 20 | \item{n}{Number of random vectors to generate.} 21 | } 22 | \value{ 23 | \code{ddirichlet} gives the density. \code{rdirichlet} returns a 24 | matrix with \code{n} rows, each containing a single Dirichlet random 25 | deviate. 26 | } 27 | \description{ 28 | Density function and random generation from the Dirichlet distribution. 29 | } 30 | \details{ 31 | The Dirichlet distribution is the multidimensional generalization of the 32 | beta distribution. 33 | } 34 | \examples{ 35 | 36 | density <- ddirichlet(c(.1,.2,.7), c(1,1,1)) 37 | draws <- rdirichlet(20, c(1,1,1) ) 38 | 39 | } 40 | \seealso{ 41 | \code{\link[stats]{Beta}} 42 | } 43 | \author{ 44 | Code is taken from Greg's Miscellaneous Functions (gregmisc). His 45 | code was based on code posted by Ben Bolker to R-News on 15 Dec 2000. 46 | } 47 | \keyword{distribution} 48 | -------------------------------------------------------------------------------- /man/Euro2016.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{Euro2016} 5 | \alias{Euro2016} 6 | \title{Euro 2016 data} 7 | \format{ 8 | This dataframe contains all of the head-to-head results from 9 | Euro 2016. This includes results from both the group stage and the 10 | knock-out rounds. 11 | \describe{ 12 | \item{dummy.rater}{An artificial "dummy" rater equal to 1 for all 13 | matches. Included so that \code{Euro2016} can be used directly with 14 | \code{MCMCpack}'s models for pairwise comparisons.} 15 | \item{team1}{The home team} 16 | \item{team2}{The away team } 17 | \item{winner}{The winner of the match. \code{NA} if a draw.} 18 | } 19 | } 20 | \source{ 21 | \url{https://en.wikipedia.org/wiki/UEFA_Euro_2016} 22 | } 23 | \description{ 24 | Data on head-to-head outcomes from the 2016 UEFA European Football 25 | Championship. 26 | } 27 | \keyword{datasets} 28 | -------------------------------------------------------------------------------- /man/InvGamma.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/distn.R 3 | \name{InvGamma} 4 | \alias{InvGamma} 5 | \alias{dinvgamma} 6 | \alias{rinvgamma} 7 | \title{The Inverse Gamma Distribution} 8 | \usage{ 9 | dinvgamma(x, shape, scale = 1) 10 | 11 | rinvgamma(n, shape, scale = 1) 12 | } 13 | \arguments{ 14 | \item{x}{Scalar location to evaluate density.} 15 | 16 | \item{shape}{Scalar shape parameter.} 17 | 18 | \item{scale}{Scalar scale parameter (default value one).} 19 | 20 | \item{n}{Number of draws from the distribution.} 21 | } 22 | \value{ 23 | \code{dinvgamma} evaluates the density at \code{x}. 24 | 25 | \code{rinvgamma} takes \code{n} draws from the inverse Gamma distribution. 26 | The parameterization is consistent with the Gamma Distribution in the stats 27 | package. 28 | } 29 | \description{ 30 | Density function and random generation from the inverse gamma distribution. 31 | } 32 | \details{ 33 | An inverse gamma random variable with shape \eqn{a} and scale \eqn{b} 34 | has mean \eqn{\frac{b}{a-1}} (assuming \eqn{a>1}) and variance 35 | \eqn{\frac{b^2}{(a-1)^2(a-2)}} (assuming \eqn{a>2}). 36 | } 37 | \examples{ 38 | 39 | density <- dinvgamma(4.2, 1.1) 40 | draws <- rinvgamma(10, 3.2) 41 | 42 | } 43 | \references{ 44 | Andrew Gelman, John B. Carlin, Hal S. Stern, and Donald B. 45 | Rubin. 2004. \emph{Bayesian Data Analysis}. 2nd Edition. Boca Raton: Chapman 46 | & Hall. 47 | } 48 | \seealso{ 49 | \code{\link[stats]{GammaDist}} 50 | } 51 | \keyword{distribution} 52 | -------------------------------------------------------------------------------- /man/InvWishart.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/distn.R 3 | \name{InvWishart} 4 | \alias{InvWishart} 5 | \alias{diwish} 6 | \alias{riwish} 7 | \title{The Inverse Wishart Distribution} 8 | \usage{ 9 | riwish(v, S) 10 | 11 | diwish(W, v, S) 12 | } 13 | \arguments{ 14 | \item{v}{Degrees of freedom (scalar).} 15 | 16 | \item{S}{Scale matrix \eqn{(p \times p)}.} 17 | 18 | \item{W}{Positive definite matrix W \eqn{(p \times p)}.} 19 | } 20 | \value{ 21 | \code{diwish} evaluates the density at positive definite matrix W. 22 | \code{riwish} generates one random draw from the distribution. 23 | } 24 | \description{ 25 | Density function and random generation from the Inverse Wishart 26 | distribution. 27 | } 28 | \details{ 29 | The mean of an inverse Wishart random variable with \code{v} degrees of 30 | freedom and scale matrix \code{S} is \eqn{(v-p-1)^{-1}S}. 31 | } 32 | \examples{ 33 | 34 | density <- diwish(matrix(c(2,-.3,-.3,4),2,2), 3, matrix(c(1,.3,.3,1),2,2)) 35 | draw <- riwish(3, matrix(c(1,.3,.3,1),2,2)) 36 | 37 | } 38 | \keyword{distribution} 39 | -------------------------------------------------------------------------------- /man/MCMCSVDreg.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCSVDreg.R 3 | \name{MCMCSVDreg} 4 | \alias{MCMCSVDreg} 5 | \title{Markov Chain Monte Carlo for SVD Regression} 6 | \usage{ 7 | MCMCSVDreg( 8 | formula, 9 | data = NULL, 10 | burnin = 1000, 11 | mcmc = 10000, 12 | thin = 1, 13 | verbose = 0, 14 | seed = NA, 15 | tau2.start = 1, 16 | g0 = 0, 17 | a0 = 0.001, 18 | b0 = 0.001, 19 | c0 = 2, 20 | d0 = 2, 21 | w0 = 1, 22 | beta.samp = FALSE, 23 | intercept = TRUE, 24 | ... 25 | ) 26 | } 27 | \arguments{ 28 | \item{formula}{Model formula. Predictions are returned for elements 29 | of y that are coded as NA.} 30 | 31 | \item{data}{Data frame.} 32 | 33 | \item{burnin}{The number of burn-in iterations for the sampler.} 34 | 35 | \item{mcmc}{The number of MCMC iterations after burnin.} 36 | 37 | \item{thin}{The thinning interval used in the simulation. The 38 | number of MCMC iterations must be divisible by this value.} 39 | 40 | \item{verbose}{A switch which determines whether or not the 41 | progress of the sampler is printed to the screen. If 42 | \code{verbose} is greater than 0 the iteration number, the 43 | \eqn{\beta} vector, and the error variance are printed to the 44 | screen every \code{verbose}th iteration.} 45 | 46 | \item{seed}{The seed for the random number generator. If NA, the 47 | Mersenne Twister generator is used with default seed 12345; if an 48 | integer is passed it is used to seed the Mersenne twister. The 49 | user can also pass a list of length two to use the L'Ecuyer 50 | random number generator, which is suitable for parallel 51 | computation. The first element of the list is the L'Ecuyer seed, 52 | which is a vector of length six or NA (if NA a default seed of 53 | \code{rep(12345,6)} is used). The second element of list is a 54 | positive substream number. See the MCMCpack specification for 55 | more details.} 56 | 57 | \item{tau2.start}{The starting values for the \eqn{\tau^2} vector. 58 | Can be either a scalar or a vector. If a scalar is passed then 59 | that value will be the starting value for all elements of 60 | \eqn{\tau^2}.} 61 | 62 | \item{g0}{The prior mean of \eqn{\gamma}. This can either be a 63 | scalar or a column vector with dimension equal to the number of 64 | gammas. If this takes a scalar value, then that value will serve 65 | as the prior mean for all of the betas.} 66 | 67 | \item{a0}{\eqn{a_0/2} is the shape parameter for the inverse Gamma 68 | prior on \eqn{\sigma^2} (the variance of the disturbances). The 69 | amount of information in the inverse Gamma prior is something 70 | like that from \eqn{a_0} pseudo-observations.} 71 | 72 | \item{b0}{\eqn{b_0/2} is the scale parameter for the inverse Gamma 73 | prior on \eqn{\sigma^2} (the variance of the disturbances). In 74 | constructing the inverse Gamma prior, \eqn{b_0} acts like the sum 75 | of squared errors from the \eqn{a_0} pseudo-observations.} 76 | 77 | \item{c0}{\eqn{c_0/2} is the shape parameter for the inverse Gamma 78 | prior on \eqn{\tau_i^2}.} 79 | 80 | \item{d0}{\eqn{d_0/2} is the scale parameter for the inverse Gamma 81 | prior on \eqn{\tau_i^2}.} 82 | 83 | \item{w0}{The prior probability that \eqn{\gamma_i = 0}. Can be 84 | either a scalar or an \eqn{N} vector where \eqn{N} is the number 85 | of observations.} 86 | 87 | \item{beta.samp}{Logical indicating whether the sampled elements of 88 | beta should be stored and returned.} 89 | 90 | \item{intercept}{Logical indicating whether the original design 91 | matrix should include a constant term.} 92 | 93 | \item{...}{further arguments to be passed} 94 | } 95 | \value{ 96 | An mcmc object that contains the posterior sample. This 97 | object can be summarized by functions provided by the coda 98 | package. 99 | } 100 | \description{ 101 | This function generates a sample from the posterior distribution of 102 | a linear regression model with Gaussian errors in which the design 103 | matrix has been decomposed with singular value decomposition.The 104 | sampling is done via the Gibbs sampling algorithm. The user 105 | supplies data and priors, and a sample from the posterior 106 | distribution is returned as an mcmc object, which can be 107 | subsequently analyzed with functions provided in the coda package. 108 | } 109 | \details{ 110 | The model takes the following form: \deqn{y = X \beta + 111 | \varepsilon} Where the errors are assumed to be iid Gaussian: 112 | \deqn{\varepsilon_{i} \sim \mathcal{N}(0, \sigma^2)} 113 | 114 | Let \eqn{N} denote the number of rows of \eqn{X} and \eqn{P} the 115 | number of columns of \eqn{X}. Unlike the standard regression setup 116 | where \eqn{N >> P} here it is the case that \eqn{P >> N}. 117 | 118 | To deal with this problem a singular value decomposition of 119 | \eqn{X'} is performed: \eqn{X' = ADF} and the regression model 120 | becomes 121 | 122 | \deqn{y = F'D \gamma + \varepsilon} 123 | 124 | where \eqn{\gamma = A' \beta} 125 | 126 | We assume the following priors: 127 | 128 | \deqn{\sigma^{-2} \sim \mathcal{G}amma(a_0/2, b_0/2)} 129 | 130 | \deqn{\tau^{-2} \sim \mathcal{G}amma(c_0/2, d_0/2)} 131 | 132 | \deqn{\gamma_i \sim w0_i \delta_0 + (1-w0_i) \mathcal{N}(g0_i, 133 | \sigma^2 \tau_i^2/ d_i^2)} 134 | 135 | where \eqn{\delta_0} is a unit point mass at 0 and \eqn{d_i} is the 136 | \eqn{i}th diagonal element of \eqn{D}. 137 | } 138 | \references{ 139 | Mike West, Josheph Nevins, Jeffrey Marks, Rainer Spang, 140 | and Harry Zuzan. 2000. ``DNA Microarray Data Analysis and 141 | Regression Modeling for Genetic Expression 142 | Profiling." Duke ISDS working paper. 143 | 144 | Gottardo, Raphael, and Adrian Raftery. 2004. ``Markov chain Monte 145 | Carlo with mixtures of singular distributions.'' Statistics 146 | Department, University of Washington, Technical Report 470. 147 | 148 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. 149 | ``MCMCpack: Markov Chain Monte Carlo in R.'', \emph{Journal of 150 | Statistical Software}. 42(9): 1-21. 151 | \doi{10.18637/jss.v042.i09}. 152 | 153 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 154 | \emph{Scythe Statistical Library 1.0.} 155 | \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 156 | 157 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. 158 | ``Output Analysis and Diagnostics for MCMC (CODA)'', \emph{R 159 | News}. 6(1): 7-11. 160 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 161 | } 162 | \seealso{ 163 | \code{\link[coda]{plot.mcmc}}, 164 | \code{\link[coda]{summary.mcmc}}, \code{\link[stats]{lm}} 165 | } 166 | \keyword{models} 167 | -------------------------------------------------------------------------------- /man/MCMCbinaryChange.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCbinaryChange.R 3 | \name{MCMCbinaryChange} 4 | \alias{MCMCbinaryChange} 5 | \title{Markov Chain Monte Carlo for a Binary Multiple Changepoint Model} 6 | \usage{ 7 | MCMCbinaryChange( 8 | data, 9 | m = 1, 10 | c0 = 1, 11 | d0 = 1, 12 | a = NULL, 13 | b = NULL, 14 | burnin = 10000, 15 | mcmc = 10000, 16 | thin = 1, 17 | verbose = 0, 18 | seed = NA, 19 | phi.start = NA, 20 | P.start = NA, 21 | marginal.likelihood = c("none", "Chib95"), 22 | ... 23 | ) 24 | } 25 | \arguments{ 26 | \item{data}{The data.} 27 | 28 | \item{m}{The number of changepoints.} 29 | 30 | \item{c0}{\eqn{c_0} is the shape1 parameter for Beta prior on 31 | \eqn{\phi} (the mean).} 32 | 33 | \item{d0}{\eqn{d_0} is the shape2 parameter for Beta prior on 34 | \eqn{\phi} (the mean).} 35 | 36 | \item{a}{\eqn{a} is the shape1 beta prior for transition 37 | probabilities. By default, the expected duration is computed and 38 | corresponding a and b values are assigned. The expected duration 39 | is the sample period divided by the number of states.} 40 | 41 | \item{b}{\eqn{b} is the shape2 beta prior for transition 42 | probabilities. By default, the expected duration is computed and 43 | corresponding a and b values are assigned. The expected duration 44 | is the sample period divided by the number of states.} 45 | 46 | \item{burnin}{The number of burn-in iterations for the sampler.} 47 | 48 | \item{mcmc}{The number of MCMC iterations after burn-in.} 49 | 50 | \item{thin}{The thinning interval used in the simulation. The 51 | number of MCMC iterations must be divisible by this value.} 52 | 53 | \item{verbose}{A switch which determines whether or not the 54 | progress of the sampler is printed to the screen. If 55 | \code{verbose} is greater than 0, the iteration number and the 56 | posterior density samples are printed to the screen every 57 | \code{verbose}th iteration.} 58 | 59 | \item{seed}{The seed for the random number generator. If NA, 60 | current R system seed is used.} 61 | 62 | \item{phi.start}{The starting values for the mean. The default 63 | value of NA will use draws from the Uniform distribution.} 64 | 65 | \item{P.start}{The starting values for the transition matrix. A 66 | user should provide a square matrix with dimension equal to the 67 | number of states. By default, draws from the \code{Beta(0.9, 68 | 0.1)} are used to construct a proper transition matrix for each 69 | raw except the last raw.} 70 | 71 | \item{marginal.likelihood}{How should the marginal likelihood be 72 | calculated? Options are: \code{none} in which case the marginal 73 | likelihood will not be calculated, and \code{Chib95} in which 74 | case the method of Chib (1995) is used.} 75 | 76 | \item{...}{further arguments to be passed} 77 | } 78 | \value{ 79 | An mcmc object that contains the posterior sample. This 80 | object can be summarized by functions provided by the coda 81 | package. The object contains an attribute \code{prob.state} 82 | storage matrix that contains the probability of \eqn{state_i} for 83 | each period, and the log-marginal likelihood of the model 84 | (\code{logmarglike}). 85 | } 86 | \description{ 87 | This function generates a sample from the posterior distribution of 88 | a binary model with multiple changepoints. The function uses the 89 | Markov chain Monte Carlo method of Chib (1998). The user supplies 90 | data and priors, and a sample from the posterior distribution is 91 | returned as an mcmc object, which can be subsequently analyzed with 92 | functions provided in the coda package. 93 | } 94 | \details{ 95 | \code{MCMCbinaryChange} simulates from the posterior distribution 96 | of a binary model with multiple changepoints. 97 | 98 | The model takes the following form: \deqn{Y_t \sim 99 | \mathcal{B}ernoulli(\phi_i),\;\; i = 1, \ldots, k} Where \eqn{k} 100 | is the number of states. 101 | 102 | We assume Beta priors for \eqn{\phi_{i}} and for transition 103 | probabilities: \deqn{\phi_i \sim \mathcal{B}eta(c_0, d_0)} And: 104 | \deqn{p_{mm} \sim \mathcal{B}eta{a}{b},\;\; m = 1, \ldots, k} Where 105 | \eqn{M} is the number of states. 106 | } 107 | \examples{ 108 | 109 | \dontrun{ 110 | set.seed(19173) 111 | true.phi<- c(0.5, 0.8, 0.4) 112 | 113 | ## two breaks at c(80, 180) 114 | y1 <- rbinom(80, 1, true.phi[1]) 115 | y2 <- rbinom(100, 1, true.phi[2]) 116 | y3 <- rbinom(120, 1, true.phi[3]) 117 | y <- as.ts(c(y1, y2, y3)) 118 | 119 | model0 <- MCMCbinaryChange(y, m=0, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 120 | marginal.likelihood = "Chib95") 121 | model1 <- MCMCbinaryChange(y, m=1, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 122 | marginal.likelihood = "Chib95") 123 | model2 <- MCMCbinaryChange(y, m=2, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 124 | marginal.likelihood = "Chib95") 125 | model3 <- MCMCbinaryChange(y, m=3, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 126 | marginal.likelihood = "Chib95") 127 | model4 <- MCMCbinaryChange(y, m=4, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 128 | marginal.likelihood = "Chib95") 129 | model5 <- MCMCbinaryChange(y, m=5, c0=2, d0=2, mcmc=100, burnin=100, verbose=50, 130 | marginal.likelihood = "Chib95") 131 | 132 | print(BayesFactor(model0, model1, model2, model3, model4, model5)) 133 | 134 | ## plot two plots in one screen 135 | par(mfrow=c(attr(model2, "m") + 1, 1), mai=c(0.4, 0.6, 0.3, 0.05)) 136 | plotState(model2, legend.control = c(1, 0.6)) 137 | plotChangepoint(model2, verbose = TRUE, ylab="Density", start=1, overlay=TRUE) 138 | 139 | } 140 | 141 | } 142 | \references{ 143 | Jong Hee Park. 2011. ``Changepoint Analysis of Binary 144 | and Ordinal Probit Models: An Application to Bank Rate Policy 145 | Under the Interwar Gold Standard." 146 | \emph{Political Analysis}. 19: 188-204. 147 | 148 | 149 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. 150 | ``MCMCpack: Markov Chain Monte Carlo in R.'', \emph{Journal of 151 | Statistical Software}. 42(9): 1-21. 152 | \doi{10.18637/jss.v042.i09}. 153 | 154 | Siddhartha Chib. 1995. ``Marginal Likelihood from the Gibbs 155 | Output.'' \emph{Journal of the American Statistical 156 | Association}. 90: 1313-1321. 157 | } 158 | \seealso{ 159 | \code{\link{MCMCpoissonChange}},\code{\link{plotState}}, 160 | \code{\link{plotChangepoint}} 161 | } 162 | \keyword{models} 163 | -------------------------------------------------------------------------------- /man/MCMCnegbin.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCnegbin.R 3 | \name{MCMCnegbin} 4 | \alias{MCMCnegbin} 5 | \title{Markov Chain Monte Carlo for Negative Binomial Regression} 6 | \usage{ 7 | MCMCnegbin( 8 | formula, 9 | data = parent.frame(), 10 | b0 = 0, 11 | B0 = 1, 12 | e = 2, 13 | f = 2, 14 | g = 10, 15 | burnin = 1000, 16 | mcmc = 1000, 17 | thin = 1, 18 | verbose = 0, 19 | seed = NA, 20 | beta.start = NA, 21 | rho.start = NA, 22 | rho.step = 0.1, 23 | nu.start = NA, 24 | marginal.likelihood = c("none", "Chib95"), 25 | ... 26 | ) 27 | } 28 | \arguments{ 29 | \item{formula}{Model formula.} 30 | 31 | \item{data}{Data frame.} 32 | 33 | \item{b0}{The prior mean of \eqn{\beta}. This can either be a scalar 34 | or a column vector with dimension equal to the number of betas. If this 35 | takes a scalar value, then that value will serve as the prior mean for all 36 | of the betas.} 37 | 38 | \item{B0}{The prior precision of \eqn{\beta}. This can either be a 39 | scalar or a square matrix with dimensions equal to the number of betas. If 40 | this takes a scalar value, then that value times an identity matrix serves 41 | as the prior precision of \eqn{\beta}. Default value of 0 is 42 | equivalent to an improper uniform prior for beta.} 43 | 44 | \item{e}{The hyperprior for the distribution \eqn{\rho}. See details.} 45 | 46 | \item{f}{The hyperprior for the distribution \eqn{\rho}. See details.} 47 | 48 | \item{g}{The hyperprior for the distribution \eqn{\rho}. See details.} 49 | 50 | \item{burnin}{The number of burn-in iterations for the sampler.} 51 | 52 | \item{mcmc}{The number of Metropolis iterations for the sampler.} 53 | 54 | \item{thin}{The thinning interval used in the simulation. The number of 55 | mcmc iterations must be divisible by this value.} 56 | 57 | \item{verbose}{A switch which determines whether or not the progress of the 58 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 59 | iteration number, the current beta vector, and the Metropolis acceptance 60 | rate are printed to the screen every \code{verbose}th iteration.} 61 | 62 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 63 | Twister generator is used with default seed 12345; if an integer is passed 64 | it is used to seed the Mersenne twister. The user can also pass a list of 65 | length two to use the L'Ecuyer random number generator, which is suitable 66 | for parallel computation. The first element of the list is the L'Ecuyer 67 | seed, which is a vector of length six or NA (if NA a default seed of 68 | \code{rep(12345,6)} is used). The second element of list is a positive 69 | substream number. See the MCMCpack specification for more details.} 70 | 71 | \item{beta.start}{The starting value for the \eqn{\beta} vector. This 72 | can either be a scalar or a column vector with dimension equal to the number 73 | of betas. If this takes a scalar value, then that value will serve as the 74 | starting value for all of the betas. The default value of NA will use the 75 | maximum likelihood estimate of \eqn{\beta} as the starting value.} 76 | 77 | \item{rho.start}{The starting value for the \eqn{\rho} variable. 78 | The default value is 1.} 79 | 80 | \item{rho.step}{Tuning parameter for the slice sampling approach to 81 | sampling \eqn{rho}. Determines the size of the step-out used to 82 | find the correct slice to draw from. Lower values are more 83 | accurate, but will take longer (up to a fixed searching limit). 84 | Default is 0.1.} 85 | 86 | \item{nu.start}{The starting values for the random effect, 87 | \eqn{\nu}. The default value is a vector of ones.} 88 | 89 | \item{marginal.likelihood}{How should the marginal likelihood be calculated? 90 | Options are: \code{none} in which case the marginal likelihood will not be 91 | calculated or \code{Laplace} in which case the Laplace approximation (see 92 | Kass and Raftery, 1995) is used.} 93 | 94 | \item{...}{further arguments to be passed.} 95 | } 96 | \value{ 97 | An mcmc object that contains the posterior sample. This object can 98 | be summarized by functions provided by the coda package. 99 | } 100 | \description{ 101 | This function generates a sample from the posterior distribution of a 102 | Negative Binomial regression model via auxiliary mixture sampling. The user 103 | supplies data and priors, and a sample from the posterior distribution is 104 | returned as an mcmc object, which can be subsequently analyzed with 105 | functions provided in the coda package. 106 | } 107 | \details{ 108 | \code{MCMCnegbin} simulates from the posterior distribution of a 109 | Negative Binomial regression model using a combination of auxiliary 110 | mixture sampling and slice sampling. The simulation proper is done 111 | in compiled C++ code to maximize efficiency. Please consult the 112 | coda documentation for a comprehensive list of functions that can 113 | be used to analyze the posterior sample. 114 | 115 | The model takes the following form: 116 | 117 | \deqn{y_i \sim \mathcal{P}oisson(\nu_i\mu_i)} 118 | 119 | Where the inverse link function: 120 | 121 | \deqn{\mu_i = \exp(x_i'\beta)} 122 | 123 | We assume a multivariate Normal prior on \eqn{\beta}: 124 | 125 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 126 | 127 | The unit-level random effect that handles overdispersion is assumed 128 | to be distributed Gamma: 129 | 130 | \deqn{\nu_i \sim \mathcal{G}amma(\rho, \rho)} 131 | 132 | The overdispersion parameter has a prior with the following form: 133 | 134 | \deqn{f(\rho|e,f,g) \propto \rho^{e-1}(\rho + g)^{-(e+f)}} 135 | 136 | The model is simulated via blocked Gibbs, with the the \eqn{\beta} 137 | being simulated via the auxiliary mixture sampling method of 138 | Fuerhwirth-Schanetter et al. (2009). The \eqn{\rho} is updated via 139 | slice sampling. The \eqn{\nu_i} are updated their (conjugate) full 140 | conditional, which is also Gamma. 141 | } 142 | \examples{ 143 | 144 | \dontrun{ 145 | n <- 150 146 | mcmcs <- 5000 147 | burnin <- 5000 148 | thin <- 5 149 | x1 <- runif(n, 0, 2) 150 | rho.true <- 1.5 151 | nu.true <- rgamma(n, rho.true, rho.true) 152 | mu <- nu.true * exp(1 + x1 * 1) 153 | y <- rpois(n, mu) 154 | posterior <- MCMCnegbin(y ~ x1) 155 | plot(posterior) 156 | summary(posterior) 157 | } 158 | 159 | } 160 | \references{ 161 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. 162 | ``MCMCpack: Markov Chain Monte Carlo in R.'', \emph{Journal of Statistical 163 | Software}. 42(9): 1-21. \doi{10.18637/jss.v042.i09}. 164 | 165 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. \emph{Scythe 166 | Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 167 | 168 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 169 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 170 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 171 | 172 | Sylvia Fruehwirth-Schnatter, Rudolf Fruehwirth, Leonhard Held, and 173 | Havard Rue. 2009. ``Improved auxiliary mixture sampling for 174 | hierarchical models of non-Gaussian data'', \emph{Statistics 175 | and Computing} 19(4): 479-492. 176 | 177 | } 178 | \seealso{ 179 | \code{\link[coda]{plot.mcmc}},\code{\link[coda]{summary.mcmc}}, 180 | \code{\link[MASS]{glm.nb}} 181 | } 182 | \keyword{models} 183 | -------------------------------------------------------------------------------- /man/MCMCpoisson.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCpoisson.R 3 | \name{MCMCpoisson} 4 | \alias{MCMCpoisson} 5 | \title{Markov Chain Monte Carlo for Poisson Regression} 6 | \usage{ 7 | MCMCpoisson( 8 | formula, 9 | data = NULL, 10 | burnin = 1000, 11 | mcmc = 10000, 12 | thin = 1, 13 | tune = 1.1, 14 | verbose = 0, 15 | seed = NA, 16 | beta.start = NA, 17 | b0 = 0, 18 | B0 = 0, 19 | marginal.likelihood = c("none", "Laplace"), 20 | ... 21 | ) 22 | } 23 | \arguments{ 24 | \item{formula}{Model formula.} 25 | 26 | \item{data}{Data frame.} 27 | 28 | \item{burnin}{The number of burn-in iterations for the sampler.} 29 | 30 | \item{mcmc}{The number of Metropolis iterations for the sampler.} 31 | 32 | \item{thin}{The thinning interval used in the simulation. The number of 33 | mcmc iterations must be divisible by this value.} 34 | 35 | \item{tune}{Metropolis tuning parameter. Can be either a positive scalar or 36 | a \eqn{k}-vector, where \eqn{k} is the length of 37 | \eqn{\beta}.Make sure that the acceptance rate is satisfactory 38 | (typically between 0.20 and 0.5) before using the posterior sample for 39 | inference.} 40 | 41 | \item{verbose}{A switch which determines whether or not the progress of the 42 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 43 | iteration number, the current beta vector, and the Metropolis acceptance 44 | rate are printed to the screen every \code{verbose}th iteration.} 45 | 46 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 47 | Twister generator is used with default seed 12345; if an integer is passed 48 | it is used to seed the Mersenne twister. The user can also pass a list of 49 | length two to use the L'Ecuyer random number generator, which is suitable 50 | for parallel computation. The first element of the list is the L'Ecuyer 51 | seed, which is a vector of length six or NA (if NA a default seed of 52 | \code{rep(12345,6)} is used). The second element of list is a positive 53 | substream number. See the MCMCpack specification for more details.} 54 | 55 | \item{beta.start}{The starting value for the \eqn{\beta} vector. This 56 | can either be a scalar or a column vector with dimension equal to the number 57 | of betas. If this takes a scalar value, then that value will serve as the 58 | starting value for all of the betas. The default value of NA will use the 59 | maximum likelihood estimate of \eqn{\beta} as the starting value.} 60 | 61 | \item{b0}{The prior mean of \eqn{\beta}. This can either be a scalar 62 | or a column vector with dimension equal to the number of betas. If this 63 | takes a scalar value, then that value will serve as the prior mean for all 64 | of the betas.} 65 | 66 | \item{B0}{The prior precision of \eqn{\beta}. This can either be a 67 | scalar or a square matrix with dimensions equal to the number of betas. If 68 | this takes a scalar value, then that value times an identity matrix serves 69 | as the prior precision of \eqn{\beta}. Default value of 0 is 70 | equivalent to an improper uniform prior for beta.} 71 | 72 | \item{marginal.likelihood}{How should the marginal likelihood be calculated? 73 | Options are: \code{none} in which case the marginal likelihood will not be 74 | calculated or \code{Laplace} in which case the Laplace approximation (see 75 | Kass and Raftery, 1995) is used.} 76 | 77 | \item{...}{further arguments to be passed.} 78 | } 79 | \value{ 80 | An mcmc object that contains the posterior sample. This object can 81 | be summarized by functions provided by the coda package. 82 | } 83 | \description{ 84 | This function generates a sample from the posterior distribution of a 85 | Poisson regression model using a random walk Metropolis algorithm. The user 86 | supplies data and priors, and a sample from the posterior distribution is 87 | returned as an mcmc object, which can be subsequently analyzed with 88 | functions provided in the coda package. 89 | } 90 | \details{ 91 | \code{MCMCpoisson} simulates from the posterior distribution of a Poisson 92 | regression model using a random walk Metropolis algorithm. The simulation 93 | proper is done in compiled C++ code to maximize efficiency. Please consult 94 | the coda documentation for a comprehensive list of functions that can be 95 | used to analyze the posterior sample. 96 | 97 | The model takes the following form: 98 | 99 | \deqn{y_i \sim \mathcal{P}oisson(\mu_i)} 100 | 101 | Where the inverse link 102 | function: 103 | 104 | \deqn{\mu_i = \exp(x_i'\beta)} 105 | 106 | We assume a multivariate Normal prior on \eqn{\beta}: 107 | 108 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 109 | 110 | The Metropois proposal distribution is centered at the current value of 111 | \eqn{\theta} and has variance-covariance \eqn{V = T (B_0 + C^{-1})^{-1} T } 112 | where \eqn{T} is a the diagonal positive definite matrix formed from the 113 | \code{tune}, \eqn{B_0} is the prior precision, and \eqn{C} is the 114 | large sample variance-covariance matrix of the MLEs. This last calculation 115 | is done via an initial call to \code{glm}. 116 | } 117 | \examples{ 118 | 119 | \dontrun{ 120 | counts <- c(18,17,15,20,10,20,25,13,12) 121 | outcome <- gl(3,1,9) 122 | treatment <- gl(3,3) 123 | posterior <- MCMCpoisson(counts ~ outcome + treatment) 124 | plot(posterior) 125 | summary(posterior) 126 | } 127 | 128 | } 129 | \references{ 130 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. 131 | ``MCMCpack: Markov Chain Monte Carlo in R.'', \emph{Journal of Statistical 132 | Software}. 42(9): 1-21. \doi{10.18637/jss.v042.i09}. 133 | 134 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. \emph{Scythe 135 | Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 136 | 137 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 138 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 139 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 140 | } 141 | \seealso{ 142 | \code{\link[coda]{plot.mcmc}},\code{\link[coda]{summary.mcmc}}, 143 | \code{\link[stats]{glm}} 144 | } 145 | \keyword{models} 146 | -------------------------------------------------------------------------------- /man/MCMCprobit.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCprobit.R 3 | \name{MCMCprobit} 4 | \alias{MCMCprobit} 5 | \title{Markov Chain Monte Carlo for Probit Regression} 6 | \usage{ 7 | MCMCprobit( 8 | formula, 9 | data = NULL, 10 | burnin = 1000, 11 | mcmc = 10000, 12 | thin = 1, 13 | verbose = 0, 14 | seed = NA, 15 | beta.start = NA, 16 | b0 = 0, 17 | B0 = 0, 18 | bayes.resid = FALSE, 19 | marginal.likelihood = c("none", "Laplace", "Chib95"), 20 | ... 21 | ) 22 | } 23 | \arguments{ 24 | \item{formula}{Model formula.} 25 | 26 | \item{data}{Data frame.} 27 | 28 | \item{burnin}{The number of burn-in iterations for the sampler.} 29 | 30 | \item{mcmc}{The number of Gibbs iterations for the sampler.} 31 | 32 | \item{thin}{The thinning interval used in the simulation. The number of 33 | Gibbs iterations must be divisible by this value.} 34 | 35 | \item{verbose}{A switch which determines whether or not the progress of the 36 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 37 | iteration number and the betas are printed to the screen every 38 | \code{verbose}th iteration.} 39 | 40 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 41 | Twister generator is used with default seed 12345; if an integer is passed 42 | it is used to seed the Mersenne twister. The user can also pass a list of 43 | length two to use the L'Ecuyer random number generator, which is suitable 44 | for parallel computation. The first element of the list is the L'Ecuyer 45 | seed, which is a vector of length six or NA (if NA a default seed of 46 | \code{rep(12345,6)} is used). The second element of list is a positive 47 | substream number. See the MCMCpack specification for more details.} 48 | 49 | \item{beta.start}{The starting value for the \eqn{\beta} vector. This 50 | can either be a scalar or a column vector with dimension equal to the number 51 | of betas. If this takes a scalar value, then that value will serve as the 52 | starting value for all of the betas. The default value of NA will use the 53 | maximum likelihood estimate of \eqn{\beta} as the starting value.} 54 | 55 | \item{b0}{The prior mean of \eqn{\beta}. This can either be a scalar 56 | or a column vector with dimension equal to the number of betas. If this 57 | takes a scalar value, then that value will serve as the prior mean for all 58 | of the betas.} 59 | 60 | \item{B0}{The prior precision of \eqn{\beta}. This can either be a 61 | scalar or a square matrix with dimensions equal to the number of betas. If 62 | this takes a scalar value, then that value times an identity matrix serves 63 | as the prior precision of \eqn{\beta}. Default value of 0 is 64 | equivalent to an improper uniform prior on \eqn{\beta}.} 65 | 66 | \item{bayes.resid}{Should latent Bayesian residuals (Albert and Chib, 1995) 67 | be returned? Default is FALSE meaning no residuals should be returned. 68 | Alternatively, the user can specify an array of integers giving the 69 | observation numbers for which latent residuals should be calculated and 70 | returned. TRUE will return draws of latent residuals for all observations.} 71 | 72 | \item{marginal.likelihood}{How should the marginal likelihood be calculated? 73 | Options are: \code{none} in which case the marginal likelihood will not be 74 | calculated, \code{Laplace} in which case the Laplace approximation (see Kass 75 | and Raftery, 1995) is used, or \code{Chib95} in which case Chib (1995) 76 | method is used.} 77 | 78 | \item{...}{further arguments to be passed} 79 | } 80 | \value{ 81 | An mcmc object that contains the posterior sample. This object can 82 | be summarized by functions provided by the coda package. 83 | } 84 | \description{ 85 | This function generates a sample from the posterior distribution of a probit 86 | regression model using the data augmentation approach of Albert and Chib 87 | (1993). The user supplies data and priors, and a sample from the posterior 88 | distribution is returned as an mcmc object, which can be subsequently 89 | analyzed with functions provided in the coda package. 90 | } 91 | \details{ 92 | \code{MCMCprobit} simulates from the posterior distribution of a probit 93 | regression model using data augmentation. The simulation proper is done in 94 | compiled C++ code to maximize efficiency. Please consult the coda 95 | documentation for a comprehensive list of functions that can be used to 96 | analyze the posterior sample. 97 | 98 | The model takes the following form: 99 | 100 | \deqn{y_i \sim \mathcal{B}ernoulli(\pi_i)} 101 | 102 | Where the inverse link function: 103 | 104 | \deqn{\pi_i = \Phi(x_i'\beta)} 105 | 106 | We assume a multivariate Normal prior on \eqn{\beta}: 107 | 108 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 109 | 110 | See Albert and Chib (1993) 111 | for estimation details. 112 | } 113 | \examples{ 114 | 115 | \dontrun{ 116 | data(birthwt) 117 | out1 <- MCMCprobit(low~as.factor(race)+smoke, data=birthwt, 118 | b0 = 0, B0 = 10, marginal.likelihood="Chib95") 119 | out2 <- MCMCprobit(low~age+as.factor(race), data=birthwt, 120 | b0 = 0, B0 = 10, marginal.likelihood="Chib95") 121 | out3 <- MCMCprobit(low~age+as.factor(race)+smoke, data=birthwt, 122 | b0 = 0, B0 = 10, marginal.likelihood="Chib95") 123 | BayesFactor(out1, out2, out3) 124 | plot(out3) 125 | summary(out3) 126 | } 127 | 128 | } 129 | \references{ 130 | Albert, J. H. and S. Chib. 1993. ``Bayesian Analysis of Binary 131 | and Polychotomous Response Data.'' \emph{J. Amer. Statist. Assoc.} 88, 132 | 669-679 133 | 134 | Albert, J. H. and S. Chib. 1995. ``Bayesian Residual Analysis for Binary 135 | Response Regression Models.'' \emph{Biometrika.} 82, 747-759. 136 | 137 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. ``MCMCpack: 138 | Markov Chain Monte Carlo in R.'', \emph{Journal of Statistical Software}. 139 | 42(9): 1-21. \doi{10.18637/jss.v042.i09}. 140 | 141 | Siddhartha Chib. 1995. ``Marginal Likelihood from the Gibbs Output.'' 142 | \emph{Journal of the American Statistical Association}. 90: 1313-1321. 143 | 144 | 145 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. \emph{Scythe 146 | Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 147 | 148 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 149 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 150 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 151 | } 152 | \seealso{ 153 | \code{\link[coda]{plot.mcmc}},\code{\link[coda]{summary.mcmc}}, 154 | \code{\link[stats]{glm}} 155 | } 156 | \keyword{models} 157 | -------------------------------------------------------------------------------- /man/MCMCquantreg.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCquantreg.R 3 | \name{MCMCquantreg} 4 | \alias{MCMCquantreg} 5 | \title{Bayesian quantile regression using Gibbs sampling} 6 | \usage{ 7 | MCMCquantreg( 8 | formula, 9 | data = NULL, 10 | tau = 0.5, 11 | burnin = 1000, 12 | mcmc = 10000, 13 | thin = 1, 14 | verbose = 0, 15 | seed = sample(1:1e+06, 1), 16 | beta.start = NA, 17 | b0 = 0, 18 | B0 = 0, 19 | ... 20 | ) 21 | } 22 | \arguments{ 23 | \item{formula}{Model formula.} 24 | 25 | \item{data}{Data frame.} 26 | 27 | \item{tau}{The quantile of interest. Must be between 0 and 1. The default 28 | value of 0.5 corresponds to median regression.} 29 | 30 | \item{burnin}{The number of burn-in iterations for the sampler.} 31 | 32 | \item{mcmc}{The number of MCMC iterations after burnin.} 33 | 34 | \item{thin}{The thinning interval used in the simulation. The number of 35 | MCMC iterations must be divisible by this value.} 36 | 37 | \item{verbose}{A switch which determines whether or not the progress of the 38 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 39 | iteration number and the most recently sampled values of \eqn{\beta} 40 | and \eqn{\sigma} are printed to the screen every \code{verbose}th 41 | iteration.} 42 | 43 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 44 | Twister generator is used with default seed 12345; if an integer is passed 45 | it is used to seed the Mersenne twister. The default value for this argument 46 | is a random integer between 1 and 1,000,000. This default value ensures that 47 | if the function is used again with a different value of \eqn{\tau}, it 48 | is extremely unlikely that the seed will be identical. The user can also 49 | pass a list of length two to use the L'Ecuyer random number generator, which 50 | is suitable for parallel computation. The first element of the list is the 51 | L'Ecuyer seed, which is a vector of length six or NA (if NA a default seed 52 | of \code{rep(12345,6)} is used). The second element of list is a positive 53 | substream number. See the MCMCpack specification for more details.} 54 | 55 | \item{beta.start}{The starting values for \eqn{\beta}. This can 56 | either be a scalar or a column vector with dimension equal to the dimension 57 | of \eqn{\beta}. The default value of NA will use the OLS estimate 58 | \eqn{\hat{\beta}} with 59 | \eqn{\hat{\sigma}\Phi^{-1}(\tau)} added on to the 60 | first element of \eqn{\hat{\beta}} as the starting value. 61 | (\eqn{\hat{\sigma}^2} denotes the usual unbiased estimator of 62 | \eqn{\sigma^2} under ordinary mean regression and 63 | \eqn{\Phi^{-1}(\tau)} denotes the inverse of the cumulative 64 | density function of the standard normal distribution.) Note that the 65 | default value assume that an intercept is included in the model. If a 66 | scalar is given, that value will serve as the starting value for all 67 | \eqn{\beta}.} 68 | 69 | \item{b0}{The prior mean of \eqn{\beta}. This can either be a scalar 70 | or a column vector with dimension equal to the dimension of 71 | 72 | \eqn{\beta}. If this takes a scalar value, then that value will serve 73 | as the prior mean for all \eqn{\beta}.} 74 | 75 | \item{B0}{The prior precision of \eqn{\beta}. This can either be a 76 | scalar or a square matrix with dimensions equal to the number of betas. If 77 | this takes a scalar value, then that value times an identity matrix serves 78 | as the prior precision of \eqn{\beta}. Default value of 0 is 79 | equivalent to an improper uniform prior for \eqn{\beta}.} 80 | 81 | \item{...}{further arguments to be passed} 82 | } 83 | \value{ 84 | An mcmc object that contains the posterior sample. This object can 85 | be summarised by functions provided by the coda package. 86 | } 87 | \description{ 88 | This function fits quantile regression models under Bayesian inference. The 89 | function samples from the posterior distribution using Gibbs sampling with 90 | data augmentation. A multivariate normal prior is assumed for 91 | \eqn{\beta}. The user supplies the prior parameters. A sample of the 92 | posterior distribution is returned as an mcmc object, which can then be 93 | analysed by functions in the coda package. 94 | } 95 | \details{ 96 | \code{MCMCquantreg} simulates from the posterior distribution using Gibbs 97 | sampling with data augmentation (see 98 | \url{http://people.brunel.ac.uk/~mastkky/}). \eqn{\beta} are drawn 99 | from a multivariate normal distribution. The augmented data are drawn 100 | conditionally from the inverse Gaussian distribution. The simulation is 101 | carried out in compiled C++ code to maximise efficiency. Please consult the 102 | coda documentation for a comprehensive list of functions that can be used to 103 | analyse the posterior sample. 104 | 105 | We assume the model 106 | 107 | \deqn{Q_{\tau}(y_i|x_i) = x_i'\beta} 108 | 109 | where \eqn{Q_{\tau}(y_i|x_i)} denotes the 110 | conditional \eqn{\tau}th quantile of \eqn{y_i} given 111 | \eqn{x_i}, and \eqn{\beta=\beta(\tau)} are the 112 | regression parameters possibly dependent on \eqn{\tau}. The likelihood 113 | is formed based on assuming independent Asymmetric Laplace distributions on 114 | the \eqn{y_i} with skewness parameter \eqn{\tau} and location 115 | parameters \eqn{x_i'\beta}. This assumption ensures that the 116 | likelihood function is maximised by the \eqn{\tau}th conditional 117 | quantile of the response variable. We assume standard, semi-conjugate 118 | priors on \eqn{\beta}: 119 | 120 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 121 | 122 | Only starting values for 123 | \eqn{\beta} are allowed for this sampler. 124 | } 125 | \examples{ 126 | 127 | \dontrun{ 128 | 129 | x<-rep(1:10,5) 130 | y<-rnorm(50,mean=x) 131 | posterior_50 <- MCMCquantreg(y~x) 132 | posterior_95 <- MCMCquantreg(y~x, tau=0.95, verbose=10000, 133 | mcmc=50000, thin=10, seed=2) 134 | plot(posterior_50) 135 | plot(posterior_95) 136 | raftery.diag(posterior_50) 137 | autocorr.plot(posterior_95) 138 | summary(posterior_50) 139 | summary(posterior_95) 140 | } 141 | 142 | } 143 | \references{ 144 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 145 | \emph{Scythe Statistical Library 1.2.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 146 | 147 | Craig Reed and Keming Yu. 2009. ``An Efficient Gibbs Sampler for Bayesian 148 | Quantile Regression.'' Technical Report. 149 | 150 | Keming Yu and Jin Zhang. 2005. ``A Three Parameter Asymmetric Laplace 151 | Distribution and it's extensions.'' \emph{Communications in Statistics - 152 | Theory and Methods}, 34, 1867-1879. 153 | 154 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 155 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 156 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 157 | } 158 | \seealso{ 159 | \code{\link[MCMCpack]{MCMCregress}}, \code{\link[coda]{plot.mcmc}}, 160 | \code{\link[coda]{summary.mcmc}}, \code{\link[stats]{lm}}, 161 | \code{\link[quantreg]{rq}} 162 | } 163 | \author{ 164 | Craig Reed 165 | } 166 | \keyword{models} 167 | -------------------------------------------------------------------------------- /man/MCMCregress.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCregress.R 3 | \name{MCMCregress} 4 | \alias{MCMCregress} 5 | \title{Markov Chain Monte Carlo for Gaussian Linear Regression} 6 | \usage{ 7 | MCMCregress( 8 | formula, 9 | data = NULL, 10 | burnin = 1000, 11 | mcmc = 10000, 12 | thin = 1, 13 | verbose = 0, 14 | seed = NA, 15 | beta.start = NA, 16 | b0 = 0, 17 | B0 = 0, 18 | c0 = 0.001, 19 | d0 = 0.001, 20 | sigma.mu = NA, 21 | sigma.var = NA, 22 | marginal.likelihood = c("none", "Laplace", "Chib95"), 23 | ... 24 | ) 25 | } 26 | \arguments{ 27 | \item{formula}{Model formula.} 28 | 29 | \item{data}{Data frame.} 30 | 31 | \item{burnin}{The number of burn-in iterations for the sampler.} 32 | 33 | \item{mcmc}{The number of MCMC iterations after burnin.} 34 | 35 | \item{thin}{The thinning interval used in the simulation. The number of 36 | MCMC iterations must be divisible by this value.} 37 | 38 | \item{verbose}{A switch which determines whether or not the progress of the 39 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 40 | iteration number, the \eqn{\beta} vector, and the error variance are 41 | printed to the screen every \code{verbose}th iteration.} 42 | 43 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 44 | Twister generator is used with default seed 12345; if an integer is passed 45 | it is used to seed the Mersenne twister. The user can also pass a list of 46 | length two to use the L'Ecuyer random number generator, which is suitable 47 | for parallel computation. The first element of the list is the L'Ecuyer 48 | seed, which is a vector of length six or NA (if NA a default seed of 49 | \code{rep(12345,6)} is used). The second element of list is a positive 50 | substream number. See the MCMCpack specification for more details.} 51 | 52 | \item{beta.start}{The starting values for the \eqn{\beta} vector. 53 | This can either be a scalar or a column vector with dimension equal to the 54 | number of betas. The default value of of NA will use the OLS estimate of 55 | \eqn{\beta} as the starting value. If this is a scalar, that value 56 | will serve as the starting value mean for all of the betas.} 57 | 58 | \item{b0}{The prior mean of \eqn{\beta}. This can either be a scalar 59 | or a column vector with dimension equal to the number of betas. If this 60 | takes a scalar value, then that value will serve as the prior mean for all 61 | of the betas.} 62 | 63 | \item{B0}{The prior precision of \eqn{\beta}. This can either be a 64 | scalar or a square matrix with dimensions equal to the number of betas. If 65 | this takes a scalar value, then that value times an identity matrix serves 66 | as the prior precision of beta. Default value of 0 is equivalent to an 67 | improper uniform prior for beta.} 68 | 69 | \item{c0}{\eqn{c_0/2} is the shape parameter for the inverse Gamma 70 | prior on \eqn{\sigma^2} (the variance of the disturbances). The 71 | amount of information in the inverse Gamma prior is something like that from 72 | \eqn{c_0} pseudo-observations.} 73 | 74 | \item{d0}{\eqn{d_0/2} is the scale parameter for the inverse Gamma 75 | prior on \eqn{\sigma^2} (the variance of the disturbances). In 76 | constructing the inverse Gamma prior, \eqn{d_0} acts like the sum of 77 | squared errors from the \eqn{c_0} pseudo-observations.} 78 | 79 | \item{sigma.mu}{The mean of the inverse Gamma prior on 80 | \eqn{\sigma^2}. \eqn{sigma.mu} and 81 | \eqn{sigma.var} allow users to choose the inverse Gamma prior by 82 | choosing its mean and variance.} 83 | 84 | \item{sigma.var}{The variacne of the inverse Gamma prior on 85 | \eqn{\sigma^2}. \eqn{sigma.mu} and 86 | \eqn{sigma.var} allow users to choose the inverse Gamma prior by 87 | choosing its mean and variance.} 88 | 89 | \item{marginal.likelihood}{How should the marginal likelihood be calculated? 90 | Options are: \code{none} in which case the marginal likelihood will not be 91 | calculated, \code{Laplace} in which case the Laplace approximation (see Kass 92 | and Raftery, 1995) is used, and \code{Chib95} in which case the method of 93 | Chib (1995) is used.} 94 | 95 | \item{...}{further arguments to be passed.} 96 | } 97 | \value{ 98 | An mcmc object that contains the posterior sample. This object can 99 | be summarized by functions provided by the coda package. 100 | } 101 | \description{ 102 | This function generates a sample from the posterior distribution of a linear 103 | regression model with Gaussian errors using Gibbs sampling (with a 104 | multivariate Gaussian prior on the beta vector, and an inverse Gamma prior 105 | on the conditional error variance). The user supplies data and priors, and 106 | a sample from the posterior distribution is returned as an mcmc object, 107 | which can be subsequently analyzed with functions provided in the coda 108 | package. 109 | } 110 | \details{ 111 | \code{MCMCregress} simulates from the posterior distribution using standard 112 | Gibbs sampling (a multivariate Normal draw for the betas, and an inverse 113 | Gamma draw for the conditional error variance). The simulation proper is 114 | done in compiled C++ code to maximize efficiency. Please consult the coda 115 | documentation for a comprehensive list of functions that can be used to 116 | analyze the posterior sample. 117 | 118 | The model takes the following form: 119 | 120 | \deqn{y_i = x_i ' \beta + \varepsilon_{i}} 121 | 122 | Where the errors are assumed to be Gaussian: 123 | 124 | \deqn{\varepsilon_{i} \sim \mathcal{N}(0, \sigma^2)} 125 | 126 | We assume standard, semi-conjugate priors: 127 | 128 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 129 | 130 | And: 131 | 132 | \deqn{\sigma^{-2} \sim \mathcal{G}amma(c_0/2, d_0/2)} 133 | 134 | Where 135 | \eqn{\beta} and \eqn{\sigma^{-2}} are assumed \emph{a 136 | priori} independent. Note that only starting values for \eqn{\beta} 137 | are allowed because simulation is done using Gibbs sampling with the 138 | conditional error variance as the first block in the sampler. 139 | } 140 | \examples{ 141 | 142 | \dontrun{ 143 | line <- list(X = c(-2,-1,0,1,2), Y = c(1,3,3,3,5)) 144 | posterior <- MCMCregress(Y~X, b0=0, B0 = 0.1, 145 | sigma.mu = 5, sigma.var = 25, data=line, verbose=1000) 146 | plot(posterior) 147 | raftery.diag(posterior) 148 | summary(posterior) 149 | } 150 | 151 | } 152 | \references{ 153 | Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park. 2011. 154 | ``MCMCpack: Markov Chain Monte Carlo in R.'', \emph{Journal of Statistical 155 | Software}. 42(9): 1-21. \doi{10.18637/jss.v042.i09}. 156 | 157 | Siddhartha Chib. 1995. ``Marginal Likelihood from the Gibbs Output.'' 158 | \emph{Journal of the American Statistical Association}. 90: 1313-1321. 159 | 160 | Robert E. Kass and Adrian E. Raftery. 1995. ``Bayes Factors.'' \emph{Journal 161 | of the American Statistical Association}. 90: 773-795. 162 | 163 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. \emph{Scythe 164 | Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 165 | 166 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 167 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 168 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 169 | } 170 | \seealso{ 171 | \code{\link[coda]{plot.mcmc}}, \code{\link[coda]{summary.mcmc}}, 172 | \code{\link[stats]{lm}} 173 | } 174 | \keyword{models} 175 | -------------------------------------------------------------------------------- /man/MCbinomialbeta.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCmodels.R 3 | \name{MCbinomialbeta} 4 | \alias{MCbinomialbeta} 5 | \title{Monte Carlo Simulation from a Binomial Likelihood with a Beta Prior} 6 | \usage{ 7 | MCbinomialbeta(y, n, alpha = 1, beta = 1, mc = 1000, ...) 8 | } 9 | \arguments{ 10 | \item{y}{The number of successes in the independent Bernoulli trials.} 11 | 12 | \item{n}{The number of independent Bernoulli trials.} 13 | 14 | \item{alpha}{Beta prior distribution alpha parameter.} 15 | 16 | \item{beta}{Beta prior distribution beta parameter.} 17 | 18 | \item{mc}{The number of Monte Carlo draws to make.} 19 | 20 | \item{...}{further arguments to be passed} 21 | } 22 | \value{ 23 | An mcmc object that contains the posterior sample. This object can 24 | be summarized by functions provided by the coda package. 25 | } 26 | \description{ 27 | This function generates a sample from the posterior distribution of a 28 | binomial likelihood with a Beta prior. 29 | } 30 | \details{ 31 | \code{MCbinomialbeta} directly simulates from the posterior distribution. 32 | This model is designed primarily for instructional use. \eqn{\pi} is 33 | the probability of success for each independent Bernoulli trial. We assume 34 | a conjugate Beta prior: 35 | 36 | \deqn{\pi \sim \mathcal{B}eta(\alpha, \beta)} 37 | 38 | \eqn{y} is the number of successes in \eqn{n} trials. By 39 | default, a uniform prior is used. 40 | } 41 | \examples{ 42 | 43 | \dontrun{ 44 | posterior <- MCbinomialbeta(3,12,mc=5000) 45 | summary(posterior) 46 | plot(posterior) 47 | grid <- seq(0,1,0.01) 48 | plot(grid, dbeta(grid, 1, 1), type="l", col="red", lwd=3, ylim=c(0,3.6), 49 | xlab="pi", ylab="density") 50 | lines(density(posterior), col="blue", lwd=3) 51 | legend(.75, 3.6, c("prior", "posterior"), lwd=3, col=c("red", "blue")) 52 | } 53 | 54 | } 55 | \seealso{ 56 | \code{\link[coda]{plot.mcmc}}, \code{\link[coda]{summary.mcmc}} 57 | } 58 | \keyword{models} 59 | -------------------------------------------------------------------------------- /man/MCmultinomdirichlet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCmodels.R 3 | \name{MCmultinomdirichlet} 4 | \alias{MCmultinomdirichlet} 5 | \title{Monte Carlo Simulation from a Multinomial Likelihood with a Dirichlet Prior} 6 | \usage{ 7 | MCmultinomdirichlet(y, alpha0, mc = 1000, ...) 8 | } 9 | \arguments{ 10 | \item{y}{A vector of data (number of successes for each category).} 11 | 12 | \item{alpha0}{The vector of parameters of the Dirichlet prior.} 13 | 14 | \item{mc}{The number of Monte Carlo draws to make.} 15 | 16 | \item{...}{further arguments to be passed} 17 | } 18 | \value{ 19 | An mcmc object that contains the posterior sample. This object can 20 | be summarized by functions provided by the coda package. 21 | } 22 | \description{ 23 | This function generates a sample from the posterior distribution of a 24 | multinomial likelihood with a Dirichlet prior. 25 | } 26 | \details{ 27 | \code{MCmultinomdirichlet} directly simulates from the posterior 28 | distribution. This model is designed primarily for instructional use. 29 | \eqn{\pi} is the parameter of interest of the multinomial distribution. 30 | It is of dimension \eqn{(d \times 1)}. We assume a conjugate 31 | Dirichlet prior: 32 | 33 | \deqn{\pi \sim \mathcal{D}irichlet(\alpha_0)} 34 | 35 | \eqn{y} is a \eqn{(d \times 1)} vector of 36 | observed data. 37 | } 38 | \examples{ 39 | 40 | \dontrun{ 41 | ## Example from Gelman, et. al. (1995, p. 78) 42 | posterior <- MCmultinomdirichlet(c(727,583,137), c(1,1,1), mc=10000) 43 | bush.dukakis.diff <- posterior[,1] - posterior[,2] 44 | cat("Pr(Bush > Dukakis): ", 45 | sum(bush.dukakis.diff > 0) / length(bush.dukakis.diff), "\n") 46 | hist(bush.dukakis.diff) 47 | } 48 | 49 | } 50 | \seealso{ 51 | \code{\link[coda]{plot.mcmc}}, \code{\link[coda]{summary.mcmc}} 52 | } 53 | \keyword{models} 54 | -------------------------------------------------------------------------------- /man/MCnormalnormal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCmodels.R 3 | \name{MCnormalnormal} 4 | \alias{MCnormalnormal} 5 | \title{Monte Carlo Simulation from a Normal Likelihood (with known variance) with a 6 | Normal Prior} 7 | \usage{ 8 | MCnormalnormal(y, sigma2, mu0, tau20, mc = 1000, ...) 9 | } 10 | \arguments{ 11 | \item{y}{The data.} 12 | 13 | \item{sigma2}{The known variance of y.} 14 | 15 | \item{mu0}{The prior mean of mu.} 16 | 17 | \item{tau20}{The prior variance of mu.} 18 | 19 | \item{mc}{The number of Monte Carlo draws to make.} 20 | 21 | \item{...}{further arguments to be passed} 22 | } 23 | \value{ 24 | An mcmc object that contains the posterior sample. This object can 25 | be summarized by functions provided by the coda package. 26 | } 27 | \description{ 28 | This function generates a sample from the posterior distribution of a Normal 29 | likelihood (with known variance) with a Normal prior. 30 | } 31 | \details{ 32 | \code{MCnormalnormal} directly simulates from the posterior distribution. 33 | This model is designed primarily for instructional use. \eqn{\mu} is 34 | the parameter of interest of the Normal distribution. We assume a conjugate 35 | normal prior: 36 | 37 | \deqn{\mu \sim \mathcal{N}(\mu_0, \tau^2_0)} 38 | 39 | \eqn{y} is a vector of observed data. 40 | } 41 | \examples{ 42 | 43 | \dontrun{ 44 | y <- c(2.65, 1.80, 2.29, 2.11, 2.27, 2.61, 2.49, 0.96, 1.72, 2.40) 45 | posterior <- MCMCpack:::MCnormalnormal(y, 1, 0, 1, 5000) 46 | summary(posterior) 47 | plot(posterior) 48 | grid <- seq(-3,3,0.01) 49 | plot(grid, dnorm(grid, 0, 1), type="l", col="red", lwd=3, ylim=c(0,1.4), 50 | xlab="mu", ylab="density") 51 | lines(density(posterior), col="blue", lwd=3) 52 | legend(-3, 1.4, c("prior", "posterior"), lwd=3, col=c("red", "blue")) 53 | } 54 | 55 | } 56 | \seealso{ 57 | \code{\link[coda]{plot.mcmc}}, \code{\link[coda]{summary.mcmc}} 58 | } 59 | \keyword{models} 60 | -------------------------------------------------------------------------------- /man/MCpoissongamma.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCmodels.R 3 | \name{MCpoissongamma} 4 | \alias{MCpoissongamma} 5 | \title{Monte Carlo Simulation from a Poisson Likelihood with a Gamma Prior} 6 | \usage{ 7 | MCpoissongamma(y, alpha, beta, mc = 1000, ...) 8 | } 9 | \arguments{ 10 | \item{y}{A vector of counts (must be non-negative).} 11 | 12 | \item{alpha}{Gamma prior distribution shape parameter.} 13 | 14 | \item{beta}{Gamma prior distribution scale parameter.} 15 | 16 | \item{mc}{The number of Monte Carlo draws to make.} 17 | 18 | \item{...}{further arguments to be passed} 19 | } 20 | \value{ 21 | An mcmc object that contains the posterior sample. This object can 22 | be summarized by functions provided by the coda package. 23 | } 24 | \description{ 25 | This function generates a sample from the posterior distribution of a 26 | Poisson likelihood with a Gamma prior. 27 | } 28 | \details{ 29 | \code{MCpoissongamma} directly simulates from the posterior distribution. 30 | This model is designed primarily for instructional use. 31 | \eqn{\lambda} is the parameter of interest of the Poisson 32 | distribution. We assume a conjugate Gamma prior: 33 | 34 | \deqn{\lambda \sim \mathcal{G}amma(\alpha, \beta)} 35 | 36 | \eqn{y} is a vector of counts. 37 | } 38 | \examples{ 39 | 40 | \dontrun{ 41 | data(quine) 42 | posterior <- MCpoissongamma(quine$Days, 15, 1, 5000) 43 | summary(posterior) 44 | plot(posterior) 45 | grid <- seq(14,18,0.01) 46 | plot(grid, dgamma(grid, 15, 1), type="l", col="red", lwd=3, ylim=c(0,1.3), 47 | xlab="lambda", ylab="density") 48 | lines(density(posterior), col="blue", lwd=3) 49 | legend(17, 1.3, c("prior", "posterior"), lwd=3, col=c("red", "blue")) 50 | } 51 | 52 | } 53 | \seealso{ 54 | \code{\link[coda]{plot.mcmc}}, \code{\link[coda]{summary.mcmc}} 55 | } 56 | \keyword{models} 57 | -------------------------------------------------------------------------------- /man/Nethvote.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{Nethvote} 5 | \alias{Nethvote} 6 | \title{Dutch Voting Behavior in 1989} 7 | \format{ 8 | A data frame with 1754 observations and 11 variables from the 1989 9 | Dutch Parliamentary Election Study (Anker and Oppenhuis, 1993). Each 10 | observation is a survey respondent. These data are a subset of one of five 11 | multiply imputed datasets used in Quinn and Martin (2002). For more 12 | information see Quinn and Martin (2002). 13 | \describe{ 14 | \item{vote}{A factor giving the self-reported vote choice of each respondent. 15 | The levels are CDA (Christen Democratisch Appel), D66 (Democraten 66), Pvda 16 | (Partij van de Arbeid), and VVD (Volkspartij voor Vrijheid en Democratie).} 17 | \item{distD66}{A numeric variable giving the squared ideological distance 18 | between the respondent and the D66. Larger values indicate ideological 19 | dissimilarity between the respondent and the party.} 20 | \item{distPvdA}{A numeric variable giving the squared ideological distance 21 | between the respondent and the PvdA. Larger values indicate ideological 22 | dissimilarity between the respondent and the party.} 23 | \item{distVVD}{A numeric variable giving the squared ideological distance between 24 | the respondent and the VVD. Larger values indicate ideological dissimilarity 25 | between the respondent and the party.} 26 | \item{distCDA}{A numeric variable giving the squared ideological 27 | distance between the respondent and the CDA. Larger values indicate 28 | ideological dissimilarity between the respondent and the party.} 29 | \item{relig}{An indicator variable equal to 0 if the respondent is not 30 | religious and 1 if the respondent is religious.} 31 | \item{class}{Social class of respondent. 0 is the lowest social class, 32 | 4 is the highest social class.} 33 | \item{income}{Income of respondent. 0 is lowest and 6 is highest.} 34 | \item{educ}{Education of respondent. 0 is lowest and 4 is highest.} 35 | \item{age}{Age category of respondent. 0 is lowest and 12 is highest.} 36 | \item{urban}{Indicator variable equal to 0 if the respondent is not a 37 | resident of an urban area and 1 if the respondent is a resident of an urban 38 | area.} 39 | } 40 | } 41 | \source{ 42 | H. Anker and E.V. Oppenhuis. 1993. ``Dutch Parliamentary Election 43 | Study.'' (computer file). Dutch Electoral Research Foundation and 44 | Netherlands Central Bureau of Statistics, Amsterdam. 45 | } 46 | \description{ 47 | Dutch Voting Behavior in 1989. 48 | } 49 | \references{ 50 | Kevin M. Quinn and Andrew D. Martin. 2002. ``An Integrated 51 | Computational Model of Multiparty Electoral Competition.'' \emph{Statistical 52 | Science}. 17: 405-419. 53 | } 54 | \keyword{datasets} 55 | -------------------------------------------------------------------------------- /man/NoncenHypergeom.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/distn.R 3 | \name{NoncenHypergeom} 4 | \alias{NoncenHypergeom} 5 | \alias{rnoncenhypergeom} 6 | \alias{dnoncenhypergeom} 7 | \title{The Noncentral Hypergeometric Distribution} 8 | \source{ 9 | J. G. Liao and Ori Rosen. 2001. ``Fast and Stable Algorithms for 10 | Computing and Sampling From the Noncentral Hypergeometric Distribution." 11 | \emph{The American Statistician.} 55: 366-369. 12 | } 13 | \usage{ 14 | dnoncenhypergeom(x = NA, n1, n2, m1, psi) 15 | 16 | rnoncenhypergeom(n, n1, n2, m1, psi) 17 | } 18 | \arguments{ 19 | \item{x}{The location to evaluate the density. If \code{x} is NA, then a 20 | matrix is returned with the density evaluated at all possible points.} 21 | 22 | \item{n1}{The size of group one.} 23 | 24 | \item{n2}{The size of group two.} 25 | 26 | \item{m1}{The observed number of positive outcomes (in both groups).} 27 | 28 | \item{psi}{Odds ratio.} 29 | 30 | \item{n}{The number of draws to make from the distribution.} 31 | } 32 | \value{ 33 | \code{dnoncenhypergeom} evaluates the density at point \code{x}, or 34 | a matrix with the first column containing the possible values of the random 35 | variable, and the second column containing the probabilities. 36 | 37 | \code{rnoncenhypergeom} returns a list of \code{n} random draws from the 38 | distribution. 39 | } 40 | \description{ 41 | Evaluates the density at a single point or all points, and generate random 42 | draws from the Noncentral Hypergeometric distribution. 43 | } 44 | \details{ 45 | The Noncentral Hypergeometric is particularly useful for conditional 46 | inference for \eqn{(2 \times 2)} tables. We use the 47 | parameterization and algorithms of Liao and Rosen (2001). The underlying R 48 | code is based on their published code. See their article for details of the 49 | parameterization. 50 | } 51 | \examples{ 52 | 53 | density <- dnoncenhypergeom(NA, 500, 500, 500, 6.0) 54 | draws <- rnoncenhypergeom(10, 500, 500, 500, 6.0) 55 | } 56 | \keyword{distribution} 57 | -------------------------------------------------------------------------------- /man/PErisk.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{PErisk} 5 | \alias{PErisk} 6 | \title{Political Economic Risk Data from 62 Countries in 1987} 7 | \format{ 8 | A data frame with 62 observations on the following 9 variables. All 9 | data points are from 1987. See Quinn (2004) for more details. 10 | \describe{ 11 | \item{country}{a factor with levels \code{Argentina} through 12 | \code{Zimbabwe}} \item{courts}{an ordered factor with levels \code{0} < 13 | \code{1}.\code{courts} is an indicator of whether the country in question is 14 | judged to have an independent judiciary. From Henisz (2002).} 15 | \item{barb2}{a numeric vector giving the natural log of the black market 16 | premium in each country. The black market premium is coded as the black market 17 | exchange rate (local currency per dollar) divided by the official exchange rate 18 | minus 1. From Marshall, Gurr, and Harff (2002). } 19 | \item{prsexp2}{an ordered factor 20 | with levels \code{0} < \code{1} < \code{2} < \code{3} < \code{4} < \code{5}, 21 | giving the lack of expropriation risk. From Marshall, Gurr, and Harff 22 | (2002).} 23 | \item{prscorr2}{an ordered factor with levels \code{0} < \code{1} < 24 | \code{2} < \code{3} < \code{4} < \code{5}, measuring the lack of corruption. 25 | From Marshall, Gurr, and Harff (2002).} 26 | \item{gdpw2}{a numeric vector giving the natural log of real GDP per worker in 27 | 1985 international prices. From Alvarez et al. (1999).} 28 | } 29 | } 30 | \source{ 31 | Mike Alvarez, Jose Antonio Cheibub, Fernando Limongi, and Adam 32 | Przeworski. 1999. ``ACLP Political and Economic Database.'' 33 | 34 | Witold J. Henisz. 2002. ``The Political Constraint Index (POLCON) Dataset.'' 35 | 36 | Monty G. Marshall, Ted Robert Gurr, and Barbara Harff. 2002. ``State Failure 37 | Task Force Problem Set.'' 38 | } 39 | \description{ 40 | Political Economic Risk Data from 62 Countries in 1987. 41 | } 42 | \references{ 43 | Kevin M. Quinn. 2004. ``Bayesian Factor Analysis for Mixed 44 | Ordinal and Continuous Response.'' \emph{Political Analyis}. 12: 338-353. 45 | } 46 | \keyword{datasets} 47 | -------------------------------------------------------------------------------- /man/PostProbMod.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/BayesFactors.R 3 | \name{PostProbMod} 4 | \alias{PostProbMod} 5 | \title{Calculate Posterior Probability of Model} 6 | \usage{ 7 | PostProbMod(BF, prior.probs = 1) 8 | } 9 | \arguments{ 10 | \item{BF}{An object of class \code{BayesFactor}.} 11 | 12 | \item{prior.probs}{The prior probabilities that each model is 13 | correct. Can be either a scalar or array. Must be positive. If 14 | the sum of the prior probabilities is not equal to 1 prior.probs 15 | will be normalized so that it does sum to unity.} 16 | } 17 | \value{ 18 | An array holding the posterior probabilities that each 19 | model under study is correct given that one of the models under 20 | study is correct. 21 | } 22 | \description{ 23 | This function takes an object of class \code{BayesFactor} and 24 | calculates the posterior probability that each model under study is 25 | correct given that one of the models under study is correct. 26 | } 27 | \examples{ 28 | 29 | \dontrun{ 30 | data(birthwt) 31 | 32 | post1 <- MCMCregress(bwt~age+lwt+as.factor(race) + smoke + ht, 33 | data=birthwt, b0=c(2700, 0, 0, -500, -500, 34 | -500, -500), 35 | B0=c(1e-6, .01, .01, 1.6e-5, 1.6e-5, 1.6e-5, 36 | 1.6e-5), c0=10, d0=4500000, 37 | marginal.likelihood="Chib95", mcmc=10000) 38 | 39 | post2 <- MCMCregress(bwt~age+lwt+as.factor(race) + smoke, 40 | data=birthwt, b0=c(2700, 0, 0, -500, -500, 41 | -500), 42 | B0=c(1e-6, .01, .01, 1.6e-5, 1.6e-5, 1.6e-5), 43 | c0=10, d0=4500000, 44 | marginal.likelihood="Chib95", mcmc=10000) 45 | 46 | post3 <- MCMCregress(bwt~as.factor(race) + smoke + ht, 47 | data=birthwt, b0=c(2700, -500, -500, 48 | -500, -500), 49 | B0=c(1e-6, 1.6e-5, 1.6e-5, 1.6e-5, 50 | 1.6e-5), c0=10, d0=4500000, 51 | marginal.likelihood="Chib95", mcmc=10000) 52 | 53 | BF <- BayesFactor(post1, post2, post3) 54 | mod.probs <- PostProbMod(BF) 55 | print(mod.probs) 56 | } 57 | 58 | } 59 | \seealso{ 60 | \code{\link{MCMCregress}} 61 | } 62 | \keyword{models} 63 | -------------------------------------------------------------------------------- /man/Rehnquist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{Rehnquist} 5 | \alias{Rehnquist} 6 | \title{U.S. Supreme Court Vote Matrix, Rehnquist Court (1994-2004)} 7 | \format{ 8 | The dataframe has contains data for justices Rehnquist, Stevens, 9 | O'Connor, Scalia, Kennedy, Souter, Thomas, Ginsburg, and Breyer for the 10 | 1994-2004 terms of the U.S. Supreme Court. The dataframe also contains the 11 | term of the case, and a time variable that counts from term 1 to 11. The 12 | votes are coded liberal (1) and conservative (0) using the protocol of 13 | Spaeth (2003). The unit of analysis is the case citation (ANALU=0). We are 14 | concerned with formally decided cases issued with written opinions, after 15 | full oral argument and cases decided by an equally divided vote 16 | (DECTYPE=1,5,6,7). 17 | } 18 | \source{ 19 | Harold J. Spaeth. 2005. \emph{Original United States Supreme Court 20 | Database: 1953-2004 Terms.} 21 | } 22 | \description{ 23 | This dataframe contains a matrix of votes cast by U.S. Supreme Court 24 | justices by all cases in the 1994-2004 terms. 25 | } 26 | \keyword{datasets} 27 | -------------------------------------------------------------------------------- /man/SSVSquantreg.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SSVSquantreg.R 3 | \name{SSVSquantreg} 4 | \alias{SSVSquantreg} 5 | \title{Stochastic search variable selection for quantile regression} 6 | \usage{ 7 | SSVSquantreg( 8 | formula, 9 | data = NULL, 10 | tau = 0.5, 11 | include = NULL, 12 | burnin = 1000, 13 | mcmc = 10000, 14 | thin = 1, 15 | verbose = 0, 16 | seed = sample(1:1e+06, 1), 17 | pi0a0 = 1, 18 | pi0b0 = 1, 19 | ... 20 | ) 21 | } 22 | \arguments{ 23 | \item{formula}{Model formula.} 24 | 25 | \item{data}{Data frame.} 26 | 27 | \item{tau}{The quantile of interest. Must be between 0 and 1. The default 28 | value of 0.5 corresponds to median regression model selection.} 29 | 30 | \item{include}{The predictor(s) that should definitely appear in the model. 31 | Can be specified by name, or their position in the formula (taking into 32 | account the intercept).} 33 | 34 | \item{burnin}{The number of burn-in iterations for the sampler.} 35 | 36 | \item{mcmc}{The number of MCMC iterations after burnin.} 37 | 38 | \item{thin}{The thinning interval used in the simulation. The number of 39 | MCMC iterations must be divisible by this value.} 40 | 41 | \item{verbose}{A switch which determines whether or not the progress of the 42 | sampler is printed to the screen. If \code{verbose} is greater than 0 the 43 | iteration number, the most recently sampled values of \eqn{\gamma} 44 | and the associated values of \eqn{\beta} are printed to the screen 45 | every \code{verbose}th iteration.} 46 | 47 | \item{seed}{The seed for the random number generator. If NA, the Mersenne 48 | Twister generator is used with default seed 12345; if an integer is passed 49 | it is used to seed the Mersenne twister. The default value for this argument 50 | is a random integer between 1 and 1,000,000. This default value ensures 51 | that if the function is used again with a different value of 52 | \eqn{\tau}, it is extremely unlikely that the seed will be identical. 53 | The user can also pass a list of length two to use the L'Ecuyer random 54 | number generator, which is suitable for parallel computation. The first 55 | element of the list is the L'Ecuyer seed, which is a vector of length six or 56 | NA (if NA a default seed of \code{rep(12345,6)} is used). The second 57 | element of list is a positive substream number. See the MCMCpack 58 | specification for more details.} 59 | 60 | \item{pi0a0, pi0b0}{Hyperparameters of the beta prior on \eqn{\pi_0}, 61 | the prior probability of including a predictor. Default values of (1,1) are 62 | equivalent to a uniform distribution.} 63 | 64 | \item{...}{Further arguments} 65 | } 66 | \value{ 67 | A list containing: 68 | 69 | \item{gamma}{The posterior sample of \eqn{\gamma}. This has 70 | associated summary and plot methods.} 71 | 72 | \item{beta}{The posterior sample of the associated regression parameters 73 | \eqn{\beta}. This can be analysed with functions from the coda 74 | package.} 75 | } 76 | \description{ 77 | This function uses stochastic search to select promising regression models 78 | at a fixed quantile \eqn{\tau}. Indicator variables 79 | \eqn{\gamma} are used to represent whether a predictor is included in 80 | the model or not. The user supplies the data and the prior distribution on 81 | the model size. A list is returned containing the posterior sample of 82 | \eqn{\gamma} and the associated regression parameters 83 | \eqn{\beta}. 84 | } 85 | \details{ 86 | \code{SSVSquantreg} implements stochastic search variable selection 87 | over a set of potential predictors to obtain promising models. The 88 | models considered take the following form: 89 | 90 | \deqn{Q_{\tau}(y_i|x_{i\gamma}) = x_{i\gamma} ' \beta_{\gamma},} 91 | 92 | where \eqn{Q_{\tau}(y_i|x_{i\gamma})} denotes the conditional 93 | \eqn{\tau}th quantile of \eqn{y_i} given \eqn{x_{i\gamma}}, 94 | \eqn{x_{i\gamma}} denotes \eqn{x_i} with those predictors 95 | \eqn{x_{ij}} for which \eqn{\gamma_j=0} removed and 96 | \eqn{\beta_{\gamma}} denotes the model specific regression 97 | parameters. 98 | 99 | The likelihood is formed based on the assumption of independent 100 | asymmetric Laplace distributions on the \eqn{y_i} with skewness 101 | parameter \eqn{\tau} and location parameters \eqn{ x_{i\gamma} ' 102 | \beta_{\gamma}}. This assumption ensures that the likelihood 103 | function is maximised by the \eqn{\tau}th conditional quantile of 104 | the response variable. 105 | 106 | The prior on each \eqn{\beta_j} is 107 | 108 | \deqn{(1-\gamma_j)\delta_0+\gamma_j\mbox{Cauchy}(0,1),} 109 | 110 | where \eqn{\delta_0} denotes a degenerate distribution with all 111 | mass at 0. A standard Cauchy distribution is chosen conditional on 112 | \eqn{\gamma_j=1}. This allows for a wider range of nonzero 113 | values of \eqn{\beta_j} than a standard Normal distribution, 114 | improving the robustness of the method. Each of the indicator variables 115 | \eqn{\gamma_j} is independently assigned a Bernoulli prior, with 116 | prior probability of inclusion \eqn{\pi_0}. This in turn is assigned 117 | a beta distribution, resulting in a beta-binomial prior on the model size. 118 | The user can supply the hyperparameters for the beta distribution. Starting 119 | values are randomly generated from the prior distribution. 120 | 121 | It is recommended to standardise any non-binary predictors in order to 122 | compare these predictors on the same scale. This can be achieved using the 123 | \code{scale} function. 124 | 125 | If it is certain that a predictor should be included, all predictors 126 | specified are brought to the first positions for computational convenience. 127 | The regression parameters associated with these predictors are given 128 | independent improper priors. Users may notice a small speed advantage if 129 | they specify the predictors that they feel certain should appear in the 130 | model, particularly for large models with a large number of observations. 131 | } 132 | \examples{ 133 | 134 | \dontrun{ 135 | 136 | set.seed(1) 137 | epsilon<-rnorm(100) 138 | set.seed(2) 139 | x<-matrix(rnorm(1000),100,10) 140 | y<-x[,1]+x[,10]+epsilon 141 | qrssvs<-SSVSquantreg(y~x) 142 | model.50pc<-SSVSquantreg(y~x) 143 | model.90pc<-SSVSquantreg(y~x,tau=0.9) 144 | summary(model.50pc) ## Intercept not in median probability model 145 | summary(model.90pc) ## Intercept appears in median probability model 146 | } 147 | 148 | } 149 | \references{ 150 | Craig Reed, David B. Dunson and Keming Yu. 2010. "Bayesian 151 | Variable Selection for Quantile Regression" Technical Report. 152 | 153 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. \emph{Scythe 154 | Statistical Library 1.2.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 155 | 156 | Keming Yu and Jin Zhang. 2005. "A Three Parameter Asymmetric Laplace 157 | Distribution and it's extensions." \emph{Communications in Statistics - 158 | Theory and Methods}, 34, 1867-1879. 159 | 160 | Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2006. ``Output 161 | Analysis and Diagnostics for MCMC (CODA)'', \emph{R News}. 6(1): 7-11. 162 | \url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-1.pdf}. 163 | } 164 | \seealso{ 165 | \code{\link[MCMCpack]{MCMCquantreg}}, 166 | \code{\link[MCMCpack]{summary.qrssvs}}, \code{\link[MCMCpack]{plot.qrssvs}}, 167 | \code{\link[MCMCpack]{mptable}}, \code{\link[MCMCpack]{topmodels}}, 168 | \code{\link[base]{scale}}, \code{\link[quantreg]{rq}} 169 | } 170 | \author{ 171 | Craig Reed 172 | } 173 | \keyword{models} 174 | -------------------------------------------------------------------------------- /man/Senate.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{Senate} 5 | \alias{Senate} 6 | \title{106th U.S. Senate Roll Call Vote Matrix} 7 | \format{ 8 | The dataframe contains roll call data for all Senators in the 106th 9 | Senate. The first column (id) is the ICPSR member ID number, the second 10 | column (statecode) is the ICPSR state code, the third column (party) is the 11 | member's state name, and the fourth column (member) is the member's name. 12 | This is followed by all roll call votes (including unanimous ones) in the 13 | 106th. Nay votes are coded 0, yea votes are coded 1, and NAs are missing 14 | votes. 15 | } 16 | \source{ 17 | Keith Poole. 2005. \emph{106th Roll Call Vote Data}. 18 | } 19 | \description{ 20 | This dataframe contains a matrix of votes cast by U.S. Senators in the 106th 21 | Congress. 22 | } 23 | \keyword{datasets} 24 | -------------------------------------------------------------------------------- /man/SupremeCourt.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{SupremeCourt} 5 | \alias{SupremeCourt} 6 | \title{U.S. Supreme Court Vote Matrix} 7 | \format{ 8 | The dataframe has contains data for justices Rehnquist, Stevens, 9 | O'Connor, Scalia, Kennedy, Souter, Thomas, Ginsburg, and Breyer for the 2000 10 | term of the U.S. Supreme Court. It contains data from 43 non-unanimous 11 | cases. The votes are coded liberal (1) and conservative (0) using the 12 | protocol of Spaeth (2003). The unit of analysis is the case citation 13 | (ANALU=0). We are concerned with formally decided cases issued with written 14 | opinions, after full oral argument and cases decided by an equally divided 15 | vote (DECTYPE=1,5,6,7). 16 | } 17 | \source{ 18 | Harold J. Spaeth. 2005. \emph{Original United States Supreme Court 19 | Database: 1953-2004 Terms.} \url{http://supremecourtdatabase.org}. 20 | } 21 | \description{ 22 | This dataframe contains a matrix votes cast by U.S. Supreme Court justices 23 | in all cases in the 2000 term. 24 | } 25 | \keyword{datasets} 26 | -------------------------------------------------------------------------------- /man/Wishart.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/distn.R 3 | \name{Wishart} 4 | \alias{Wishart} 5 | \alias{dwish} 6 | \alias{rwish} 7 | \title{The Wishart Distribution} 8 | \usage{ 9 | rwish(v, S) 10 | 11 | dwish(W, v, S) 12 | } 13 | \arguments{ 14 | \item{v}{Degrees of freedom (scalar).} 15 | 16 | \item{S}{Inverse scale matrix \eqn{(p \times p)}.} 17 | 18 | \item{W}{Positive definite matrix W \eqn{(p \times p)}.} 19 | } 20 | \value{ 21 | \code{dwish} evaluates the density at positive definite matrix W. 22 | \code{rwish} generates one random draw from the distribution. 23 | } 24 | \description{ 25 | Density function and random generation from the Wishart distribution. 26 | } 27 | \details{ 28 | The mean of a Wishart random variable with \code{v} degrees of freedom and 29 | inverse scale matrix \code{S} is \eqn{vS}. 30 | } 31 | \examples{ 32 | 33 | density <- dwish(matrix(c(2,-.3,-.3,4),2,2), 3, matrix(c(1,.3,.3,1),2,2)) 34 | draw <- rwish(3, matrix(c(1,.3,.3,1),2,2)) 35 | 36 | } 37 | \keyword{distribution} 38 | -------------------------------------------------------------------------------- /man/choicevar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MCMCmnl.R 3 | \name{choicevar} 4 | \alias{choicevar} 5 | \title{Handle Choice-Specific Covariates in Multinomial Choice Models} 6 | \usage{ 7 | choicevar(var, varname, choicelevel) 8 | } 9 | \arguments{ 10 | \item{var}{The is the name of the variable in the dataframe.} 11 | 12 | \item{varname}{The name of the new variable to be created.} 13 | 14 | \item{choicelevel}{The level of \code{y} that the variable corresponds to.} 15 | } 16 | \value{ 17 | The new variable used by the \code{MCMCmnl()} function. 18 | } 19 | \description{ 20 | This function handles choice-specific covariates in multinomial choice 21 | models. See the example for an example of useage. 22 | } 23 | \seealso{ 24 | \code{\link{MCMCmnl}} 25 | } 26 | \keyword{manip} 27 | -------------------------------------------------------------------------------- /man/dtomogplot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/tomog.R 3 | \name{dtomogplot} 4 | \alias{dtomogplot} 5 | \title{Dynamic Tomography Plot} 6 | \usage{ 7 | dtomogplot( 8 | r0, 9 | r1, 10 | c0, 11 | c1, 12 | time.vec = NA, 13 | delay = 0, 14 | xlab = "fraction of r0 in c0 (p0)", 15 | ylab = "fraction of r1 in c0 (p1)", 16 | color.palette = heat.colors, 17 | bgcol = "black", 18 | ... 19 | ) 20 | } 21 | \arguments{ 22 | \item{r0}{An \eqn{(ntables \times 1)} vector of row sums from 23 | row 0.} 24 | 25 | \item{r1}{An \eqn{(ntables \times 1)} vector of row sums from 26 | row 1.} 27 | 28 | \item{c0}{An \eqn{(ntables \times 1)} vector of column sums 29 | from column 0.} 30 | 31 | \item{c1}{An \eqn{(ntables \times 1)} vector of column sums 32 | from column 1.} 33 | 34 | \item{time.vec}{Vector of time periods that correspond to the elements of 35 | \eqn{r_0}, \eqn{r_1}, \eqn{c_0}, and \eqn{c_1}.} 36 | 37 | \item{delay}{Time delay in seconds between the plotting of the tomography 38 | lines. Setting a positive delay is useful for visualizing temporal 39 | dependence.} 40 | 41 | \item{xlab}{The x axis label for the plot.} 42 | 43 | \item{ylab}{The y axis label for the plot.} 44 | 45 | \item{color.palette}{Color palette to be used to encode temporal patterns.} 46 | 47 | \item{bgcol}{The background color for the plot.} 48 | 49 | \item{...}{further arguments to be passed} 50 | } 51 | \description{ 52 | dtomogplot is used to produce a tomography plot (see King, 1997) for a 53 | series of temporally ordered, partially observed 2 x 2 contingency tables. 54 | } 55 | \details{ 56 | Consider the following partially observed 2 by 2 contingency table: 57 | 58 | \tabular{llll}{ 59 | \tab | \eqn{Y=0} \tab | \eqn{Y=1} \tab | \cr 60 | --------- \tab --------- \tab --------- \tab --------- \cr 61 | \eqn{X=0} \tab | \eqn{Y_0} \tab | \tab | \eqn{r_0} \cr 62 | --------- \tab --------- \tab --------- \tab --------- \cr 63 | \eqn{X=1} \tab | \eqn{Y_1} \tab | \tab | \eqn{r_1} \cr 64 | --------- \tab --------- \tab --------- \tab --------- \cr 65 | \tab | \eqn{c_0} \tab | \eqn{c_1} \tab | \eqn{N} 66 | } 67 | where \eqn{r_0}, \eqn{r_1}, \eqn{c_0}, \eqn{c_1}, and 68 | \eqn{N} are non-negative integers that are observed. The interior cell 69 | entries are not observed. It is assumed that \eqn{Y_0|r_0 \sim 70 | \mathcal{B}inomial(r_0, p_0)} and \eqn{Y_1|r_1 \sim \mathcal{B}inomial(r_1, p_1)}. 71 | 72 | This function plots the bounds on the maximum likelihood estimates for (p0, 73 | p1) and color codes them by the elements of time.vec. 74 | } 75 | \examples{ 76 | 77 | \dontrun{ 78 | ## simulated data example 1 79 | set.seed(3920) 80 | n <- 100 81 | r0 <- rpois(n, 2000) 82 | r1 <- round(runif(n, 100, 4000)) 83 | p0.true <- pnorm(-1.5 + 1:n/(n/2)) 84 | p1.true <- pnorm(1.0 - 1:n/(n/4)) 85 | y0 <- rbinom(n, r0, p0.true) 86 | y1 <- rbinom(n, r1, p1.true) 87 | c0 <- y0 + y1 88 | c1 <- (r0+r1) - c0 89 | 90 | ## plot data 91 | dtomogplot(r0, r1, c0, c1, delay=0.1) 92 | 93 | ## simulated data example 2 94 | set.seed(8722) 95 | n <- 100 96 | r0 <- rpois(n, 2000) 97 | r1 <- round(runif(n, 100, 4000)) 98 | p0.true <- pnorm(-1.0 + sin(1:n/(n/4))) 99 | p1.true <- pnorm(0.0 - 2*cos(1:n/(n/9))) 100 | y0 <- rbinom(n, r0, p0.true) 101 | y1 <- rbinom(n, r1, p1.true) 102 | c0 <- y0 + y1 103 | c1 <- (r0+r1) - c0 104 | 105 | ## plot data 106 | dtomogplot(r0, r1, c0, c1, delay=0.1) 107 | } 108 | 109 | } 110 | \references{ 111 | Gary King, 1997. \emph{A Solution to the Ecological Inference 112 | Problem}. Princeton: Princeton University Press. 113 | 114 | Jonathan C. Wakefield. 2004. ``Ecological Inference for 2 x 2 Tables.'' 115 | \emph{Journal of the Royal Statistical Society, Series A}. 167(3): 385445. 116 | 117 | Kevin Quinn. 2004. ``Ecological Inference in the Presence of Temporal 118 | Dependence." In \emph{Ecological Inference: New Methodological Strategies}. 119 | Gary King, Ori Rosen, and Martin A. Tanner (eds.). New York: Cambridge 120 | University Press. 121 | } 122 | \seealso{ 123 | \code{\link{MCMChierEI}}, 124 | \code{\link{MCMCdynamicEI}},\code{\link{tomogplot}} 125 | } 126 | \keyword{hplot} 127 | -------------------------------------------------------------------------------- /man/make.breaklist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/make.breaklist.R 3 | \name{make.breaklist} 4 | \alias{make.breaklist} 5 | \title{Vector of break numbers} 6 | \usage{ 7 | make.breaklist(BF, threshold = 3) 8 | } 9 | \arguments{ 10 | \item{BF}{output of \code{testpanelSubjectBreak}.} 11 | 12 | \item{threshold}{The Bayes Factor threshold to pick the best model. If a 13 | Bayes factor of two models is smaller than \code{threshold}, the model with 14 | a smaller number of break is chosen to avoid the over-identification 15 | problem. Users can change threshold into any positive number. The default 16 | value of 3 is chosen as it indicates the existence of "substantial evidence" 17 | in favor of the model in the numerator according to Jeffreys' scale.} 18 | } 19 | \value{ 20 | Vector fo break numbers. 21 | } 22 | \description{ 23 | This function generates a vector of break numbers using the output of 24 | \code{testpanelSubjectBreak}. The function performs a pairwise comparison 25 | of models using Bayes Factors. 26 | } 27 | \references{ 28 | Jong Hee Park, 2012. ``Unified Method for Dynamic and 29 | Cross-Sectional Heterogeneity: Introducing Hidden Markov Panel 30 | Models.'' \emph{American Journal of Political Science}.56: 31 | 1040-1054. 32 | 33 | Harold Jeffreys, 1961. The Theory of Probability. Oxford University Press. 34 | } 35 | \seealso{ 36 | \code{\link{testpanelSubjectBreak}} 37 | } 38 | -------------------------------------------------------------------------------- /man/mptable.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SSVSquantregsummary.R 3 | \name{mptable} 4 | \alias{mptable} 5 | \title{Calculate the marginal posterior probabilities of predictors being included 6 | in a quantile regression model.} 7 | \usage{ 8 | mptable(qrssvs) 9 | } 10 | \arguments{ 11 | \item{qrssvs}{An object of class \code{qrssvs}. Typically this will be the 12 | \code{gamma} component of the list returned by \code{SSVSquantreg}.} 13 | } 14 | \value{ 15 | A table with the predictors listed together with their posterior 16 | marginal posterior probability of inclusion. 17 | } 18 | \description{ 19 | This function extracts the marginal probability table produced by 20 | \code{summary.qrssvs}. 21 | } 22 | \examples{ 23 | 24 | \dontrun{ 25 | set.seed(1) 26 | epsilon<-rnorm(100) 27 | set.seed(2) 28 | x<-matrix(rnorm(1000),100,10) 29 | y<-x[,1]+x[,10]+epsilon 30 | qrssvs<-SSVSquantreg(y~x) 31 | mptable(qrssvs$gamma) 32 | } 33 | 34 | } 35 | \seealso{ 36 | \code{\link[MCMCpack]{SSVSquantreg}} 37 | } 38 | \author{ 39 | Craig Reed 40 | } 41 | \keyword{models} 42 | -------------------------------------------------------------------------------- /man/plot.qrssvs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SSVSquantregsummary.R 3 | \name{plot.qrssvs} 4 | \alias{plot.qrssvs} 5 | \title{Plot output from quantile regression stochastic search variable selection 6 | (QR-SSVS).} 7 | \usage{ 8 | \method{plot}{qrssvs}(x, ...) 9 | } 10 | \arguments{ 11 | \item{x}{An object of class \code{qrssvs}. Typically this will be the 12 | \code{gamma} component of the list returned by \code{SSVSquantreg}.} 13 | 14 | \item{...}{Further arguments} 15 | } 16 | \value{ 17 | An object with class \code{"trellis"}. The associated 18 | \code{\link[lattice:update.trellis]{update}} and 19 | \code{\link[lattice:print.trellis]{print}} methods are documented in the 20 | "Lattice" package. 21 | } 22 | \description{ 23 | This function produces a Trellis plot of the predictors on the y-axis versus 24 | the marginal posterior probability of inclusion on the x-axis. 25 | } 26 | \examples{ 27 | 28 | \dontrun{ 29 | set.seed(1) 30 | epsilon<-rnorm(100) 31 | set.seed(2) 32 | x<-matrix(rnorm(1000),100,10) 33 | y<-x[,1]+x[,10]+epsilon 34 | qrssvs<-SSVSquantreg(y~x) 35 | plot(qrssvs$gamma) 36 | ## Modify the graph by increasing the fontsize on the axes 37 | qrssvsplot<-plot(qrssvs$gamma) 38 | update(qrssvsplot, scales=list(cex=3)) 39 | } 40 | 41 | } 42 | \references{ 43 | Deepayan Sarkar. 2008. \emph{lattice: Lattice Graphics.} R package version 44 | 0.17-17 45 | } 46 | \seealso{ 47 | \code{\link[MCMCpack]{SSVSquantreg}}, 48 | \code{\link[MCMCpack]{mptable}}, \code{\link[lattice:Lattice]{Lattice}} for 49 | a brief introduction to lattice displays and links to further documentation. 50 | } 51 | \author{ 52 | Craig Reed 53 | } 54 | \keyword{models} 55 | -------------------------------------------------------------------------------- /man/plotChangepoint.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/btsutil.R 3 | \name{plotChangepoint} 4 | \alias{plotChangepoint} 5 | \title{Posterior Density of Regime Change Plot} 6 | \usage{ 7 | plotChangepoint( 8 | mcmcout, 9 | main = "Posterior Density of Regime Change Probabilities", 10 | xlab = "Time", 11 | ylab = "", 12 | verbose = FALSE, 13 | start = 1, 14 | overlay = FALSE 15 | ) 16 | } 17 | \arguments{ 18 | \item{mcmcout}{The \code{mcmc} object containing the posterior density 19 | sample from a changepoint model. Note that this must have a 20 | 21 | \code{prob.state} attribute.} 22 | 23 | \item{main}{Title of the plot} 24 | 25 | \item{xlab}{Label for the x-axis.} 26 | 27 | \item{ylab}{Label for the y-axis.} 28 | 29 | \item{verbose}{If \code{verbose=TRUE}, expected changepoints are printed.} 30 | 31 | \item{start}{The time of the first observation to be shown in the time 32 | series plot.} 33 | 34 | \item{overlay}{If \code{overlay=TRUE}, the probability of each regime change is 35 | drawn separately, which will be useful to draw multiple plots in one screen. 36 | See the example in \code{MCMCpoissonChange}. Otherwise, multiple plots of 37 | regime change probabilities will be drawn.} 38 | } 39 | \description{ 40 | Plot the posterior density of regime change. 41 | } 42 | \seealso{ 43 | \code{\link{MCMCpoissonChange}}, \code{\link{MCMCbinaryChange}} 44 | } 45 | \keyword{hplot} 46 | -------------------------------------------------------------------------------- /man/plotHDPChangepoint.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/hdp-utils.R 3 | \name{plotHDPChangepoint} 4 | \alias{plotHDPChangepoint} 5 | \title{Posterior Changepoint Probabilities from HDP-HMM} 6 | \usage{ 7 | plotHDPChangepoint( 8 | mcmcout, 9 | main = "Posterior Changepoint Probabilities", 10 | xlab = "Time", 11 | ylab = "", 12 | start = 1 13 | ) 14 | } 15 | \arguments{ 16 | \item{mcmcout}{The \code{mcmc} object containing the posterior density 17 | sample from a changepoint model. Note that this must be from a 18 | HDP-HMM sampler.} 19 | 20 | \item{main}{Title of the plot} 21 | 22 | \item{xlab}{Label for the x-axis.} 23 | 24 | \item{ylab}{Label for the y-axis.} 25 | 26 | \item{start}{The time of the first observation to be shown in the time 27 | series plot.} 28 | } 29 | \description{ 30 | Plot the posterior density of regime change. 31 | } 32 | \seealso{ 33 | \code{\link{HDPHMMpoisson}}, \code{\link{HDPHMMnegbin}}, \code{\link{HDPHSMMnegbin}} 34 | } 35 | \keyword{hplot} 36 | -------------------------------------------------------------------------------- /man/plotState.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/btsutil.R 3 | \name{plotState} 4 | \alias{plotState} 5 | \title{Changepoint State Plot} 6 | \usage{ 7 | plotState( 8 | mcmcout, 9 | main = "Posterior Regime Probability", 10 | ylab = expression(paste("Pr(", S[t], "= k |", Y[t], ")")), 11 | legend.control = NULL, 12 | cex = 0.8, 13 | lwd = 1.2, 14 | start = 1 15 | ) 16 | } 17 | \arguments{ 18 | \item{mcmcout}{The \code{mcmc} object containing the posterior density 19 | sample from a changepoint model. Note that this must have a 20 | \code{prob.state} attribute.} 21 | 22 | \item{main}{Title of the plot.} 23 | 24 | \item{ylab}{Label for the y-axis.} 25 | 26 | \item{legend.control}{Control the location of the legend. It is necessary 27 | to pass both the x and y locations; i.e., \code{c(x,y)}.} 28 | 29 | \item{cex}{Control point size.} 30 | 31 | \item{lwd}{Line width parameter.} 32 | 33 | \item{start}{The time of the first observation to be shown in the time 34 | series plot.} 35 | } 36 | \description{ 37 | Plot the posterior probability that each time point is in each state. 38 | } 39 | \seealso{ 40 | \code{\link{MCMCpoissonChange}}, \code{\link{MCMCbinaryChange}} 41 | } 42 | \keyword{hplot} 43 | -------------------------------------------------------------------------------- /man/procrustes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/procrust.R 3 | \name{procrustes} 4 | \alias{procrustes} 5 | \title{Procrustes Transformation} 6 | \usage{ 7 | procrustes(X, Xstar, translation = FALSE, dilation = FALSE) 8 | } 9 | \arguments{ 10 | \item{X}{The matrix to be transformed.} 11 | 12 | \item{Xstar}{The target matrix.} 13 | 14 | \item{translation}{logical value indicating whether \code{X} should be 15 | translated.} 16 | 17 | \item{dilation}{logical value indicating whether \code{X} should be dilated.} 18 | } 19 | \value{ 20 | A list containing: \code{X.new} the matrix that is the Procrustes 21 | transformed version of \code{X}, \code{R} the rotation matrix, \code{tt} the 22 | translation vector, and \code{s} the scale factor. 23 | } 24 | \description{ 25 | This function performs a Procrustes transformation on a matrix \code{X} to 26 | minimize the squared distance between \code{X} and another matrix 27 | \code{Xstar}. 28 | } 29 | \details{ 30 | \code{R}, \code{tt}, and \code{s} are chosen so that: 31 | 32 | \deqn{s X R + 1 tt' \approx X^*} 33 | 34 | \code{X.new} is given by: 35 | 36 | \deqn{X_{new} = s X R + 1 tt'} 37 | } 38 | \references{ 39 | Borg and Groenen. 1997. \emph{Modern Multidimensional Scaling}. 40 | New York: Springer. pp. 340-342. 41 | } 42 | \seealso{ 43 | \code{\link{MCMCirtKd}} 44 | } 45 | \keyword{manip} 46 | -------------------------------------------------------------------------------- /man/read.Scythe.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/scythe.R 3 | \name{read.Scythe} 4 | \alias{read.Scythe} 5 | \title{Read a Matrix from a File written by Scythe} 6 | \usage{ 7 | read.Scythe(infile = NA) 8 | } 9 | \arguments{ 10 | \item{infile}{The file to be read. This can include path information.} 11 | } 12 | \value{ 13 | A matrix containing the data stored in the read file. 14 | } 15 | \description{ 16 | This function reads a matrix from an ASCII file in the form produced by the 17 | Scythe Statistical Library. Scythe output files contain the number of rows 18 | and columns in the first row, followed by the data. 19 | } 20 | \examples{ 21 | 22 | \dontrun{ 23 | mymatrix <- read.Scythe("myfile.txt") 24 | } 25 | 26 | } 27 | \references{ 28 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 29 | \emph{Scythe Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 30 | } 31 | \seealso{ 32 | \code{\link{write.Scythe}} 33 | } 34 | \keyword{file} 35 | -------------------------------------------------------------------------------- /man/summaryqrssvs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SSVSquantregsummary.R 3 | \name{summaryqrssvs} 4 | \alias{summaryqrssvs} 5 | \alias{summary.qrssvs} 6 | \alias{print.summary.qrssvs} 7 | \title{Summarising the results of quantile regression stochastic search variable 8 | selection (QR-SSVS).} 9 | \usage{ 10 | \method{summary}{qrssvs}(object, ...) 11 | } 12 | \arguments{ 13 | \item{object}{An object of class \code{qrssvs}. Typically this will be the 14 | \code{gamma} component of the list returned by \code{SSVSquantreg}.} 15 | 16 | \item{...}{Further arguments.} 17 | } 18 | \description{ 19 | This function produces a table of predictors and their associated marginal 20 | posterior probability of inclusion. It also returns the median probability 21 | model (see the details section). 22 | } 23 | \details{ 24 | The median probability model is defined to be the model that contains any 25 | predictor with marginal posterior probability greater than or equal to 0.5. 26 | If the goal is to select a single model e.g. for prediction, Barbieri and 27 | Berger (2004) recommend the median probability model. In some cases, this 28 | will coincide with the maximum probability model. 29 | } 30 | \examples{ 31 | 32 | \dontrun{ 33 | set.seed(1) 34 | epsilon<-rnorm(100) 35 | set.seed(2) 36 | x<-matrix(rnorm(1000),100,10) 37 | y<-x[,1]+x[,10]+epsilon 38 | qrssvs<-SSVSquantreg(y~x) 39 | summary(qrssvs$gamma) 40 | } 41 | 42 | } 43 | \references{ 44 | Maria M. Barbieri, and James O. Berger (2004). "Optimal predictive model 45 | selection". \emph{Annals of Statistics}, 32, 870-897. 46 | } 47 | \seealso{ 48 | \code{\link[MCMCpack]{SSVSquantreg}}, 49 | \code{\link[MCMCpack]{mptable}}, \code{\link[MCMCpack]{topmodels}} 50 | } 51 | \author{ 52 | Craig Reed 53 | } 54 | \keyword{models} 55 | -------------------------------------------------------------------------------- /man/testpanelSubjectBreak.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testpanelSubjectBreak.R 3 | \name{testpanelSubjectBreak} 4 | \alias{testpanelSubjectBreak} 5 | \title{A Test for the Subject-level Break using a Unitivariate Linear Regression 6 | Model with Breaks} 7 | \usage{ 8 | testpanelSubjectBreak( 9 | subject.id, 10 | time.id, 11 | resid, 12 | max.break = 2, 13 | minimum = 10, 14 | mcmc = 1000, 15 | burnin = 1000, 16 | thin = 1, 17 | verbose = 0, 18 | b0, 19 | B0, 20 | c0, 21 | d0, 22 | a = NULL, 23 | b = NULL, 24 | seed = NA, 25 | Time = NULL, 26 | ps.out = FALSE, 27 | ... 28 | ) 29 | } 30 | \arguments{ 31 | \item{subject.id}{A numeric vector indicating the group number. It should 32 | start from 1.} 33 | 34 | \item{time.id}{A numeric vector indicating the time unit. It should start 35 | from 1.} 36 | 37 | \item{resid}{A vector of panel residuals.} 38 | 39 | \item{max.break}{An upper bound of break numbers for the test.} 40 | 41 | \item{minimum}{A minimum length of time series for the test. The test will 42 | skip a subject with a time series shorter than this.} 43 | 44 | \item{mcmc}{The number of MCMC iterations after burn-in.} 45 | 46 | \item{burnin}{The number of burn-in iterations for the sampler.} 47 | 48 | \item{thin}{The thinning interval used in the simulation. The number of 49 | MCMC iterations must be divisible by this value.} 50 | 51 | \item{verbose}{A switch which determines whether or not the progress of the 52 | sampler is printed to the screen. If \code{verbose} is greater than 0, the 53 | iteration number and the posterior density samples are printed to the screen 54 | every \code{verbose}th iteration.} 55 | 56 | \item{b0}{The prior mean of the residual mean.} 57 | 58 | \item{B0}{The prior precision of the residual variance} 59 | 60 | \item{c0}{\eqn{c_0/2} is the shape parameter for the inverse Gamma 61 | prior on \eqn{\sigma^2}. The amount of information in the inverse 62 | Gamma prior is something like that from \eqn{c_0} pseudo-observations.} 63 | 64 | \item{d0}{\eqn{d_0/2} is the scale parameter for the inverse Gamma 65 | prior on \eqn{\sigma^2}.} 66 | 67 | \item{a}{\eqn{a} is the shape1 beta prior for transition probabilities. 68 | By default, the expected duration is computed and corresponding a and b 69 | values are assigned. The expected duration is the sample period divided by 70 | the number of states.} 71 | 72 | \item{b}{\eqn{b} is the shape2 beta prior for transition probabilities. 73 | By default, the expected duration is computed and corresponding a and b 74 | values are assigned. The expected duration is the sample period divided by 75 | the number of states.} 76 | 77 | \item{seed}{The seed for the random number generator. If NA, current R 78 | system seed is used.} 79 | 80 | \item{Time}{Times of the observations. This will be used to find the time of 81 | the first observations in panel residuals.} 82 | 83 | \item{ps.out}{If ps.out == TRUE, state probabilities are exported. If the 84 | number of panel subjects is huge, users can turn it off to save memory.} 85 | 86 | \item{...}{further arguments to be passed} 87 | } 88 | \value{ 89 | The returned object is a matrix containing log marginal likelihoods 90 | for all HMMs. The dimension of the returned object is the number of panel 91 | subjects by max.break + 1. If psout == TRUE, the returned object has an 92 | array attribute \code{psout} containing state probabilities for all HMMs. 93 | } 94 | \description{ 95 | testpanelSubjectBreak fits a unitivariate linear regression model with 96 | parametric breaks using panel residuals to test the existence of 97 | subject-level breaks in panel residuals. The details are discussed in Park 98 | (2011). 99 | } 100 | \details{ 101 | \code{testpanelSubjectBreak} fits a univariate linear regression model for 102 | subject-level residuals from a panel model. The details are discussed in 103 | Park (2011). 104 | 105 | The model takes the following form: 106 | 107 | \deqn{e_{it} = \alpha_{im} + \varepsilon_{it}\;\; m = 1, \ldots, M} 108 | 109 | The errors are assumed to be time-varying at the subject level: 110 | 111 | \deqn{\varepsilon_{it} \sim \mathcal{N}(0, \sigma^2_{im})} 112 | 113 | We assume standard, semi-conjugate priors: 114 | 115 | \deqn{\beta \sim \mathcal{N}(b_0,B_0^{-1})} 116 | 117 | And: 118 | 119 | \deqn{\sigma^{-2} \sim \mathcal{G}amma(c_0/2, d_0/2)} 120 | 121 | Where \eqn{\beta} and \eqn{\sigma^{-2}} are assumed \emph{a priori} 122 | independent. 123 | 124 | And: 125 | 126 | \deqn{p_{mm} \sim \mathcal{B}eta(a, b),\;\; m = 1, \ldots, M} 127 | 128 | Where \eqn{M} is the number of states. 129 | 130 | OLS estimates are used for starting values. 131 | } 132 | \examples{ 133 | 134 | \dontrun{ 135 | set.seed(1974) 136 | N <- 30 137 | T <- 80 138 | NT <- N*T 139 | 140 | ## true parameter values 141 | true.beta <- c(1, 1) 142 | true.sigma <- 3 143 | x1 <- rnorm(NT) 144 | x2 <- runif(NT, 2, 4) 145 | 146 | ## group-specific breaks 147 | break.point = rep(T/2, N); break.sigma=c(rep(1, N)); 148 | break.list <- rep(1, N) 149 | 150 | X <- as.matrix(cbind(x1, x2), NT, ); 151 | y <- rep(NA, NT) 152 | id <- rep(1:N, each=NT/N) 153 | K <- ncol(X); 154 | true.beta <- as.matrix(true.beta, K, 1) 155 | 156 | ## compute the break probability 157 | ruler <- c(1:T) 158 | W.mat <- matrix(NA, T, N) 159 | for (i in 1:N){ 160 | W.mat[, i] <- pnorm((ruler-break.point[i])/break.sigma[i]) 161 | } 162 | Weight <- as.vector(W.mat) 163 | 164 | ## draw time-varying individual effects and sample y 165 | j = 1 166 | true.sigma.alpha <- 30 167 | true.alpha1 <- true.alpha2 <- rep(NA, N) 168 | for (i in 1:N){ 169 | Xi <- X[j:(j+T-1), ] 170 | true.mean <- Xi \%*\% true.beta 171 | weight <- Weight[j:(j+T-1)] 172 | true.alpha1[i] <- rnorm(1, 0, true.sigma.alpha) 173 | true.alpha2[i] <- -1*true.alpha1[i] 174 | y[j:(j+T-1)] <- ((1-weight)*true.mean + (1-weight)*rnorm(T, 0, true.sigma) + 175 | (1-weight)*true.alpha1[i]) + 176 | (weight*true.mean + weight*rnorm(T, 0, true.sigma) + weight*true.alpha2[i]) 177 | j <- j + T 178 | } 179 | 180 | ## extract the standardized residuals from the OLS with fixed-effects 181 | FEols <- lm(y ~ X + as.factor(id) -1 ) 182 | resid.all <- rstandard(FEols) 183 | time.id <- rep(1:80, N) 184 | 185 | ## model fitting 186 | G <- 1000 187 | BF <- testpanelSubjectBreak(subject.id=id, time.id=time.id, 188 | resid= resid.all, max.break=3, minimum = 10, 189 | mcmc=G, burnin = G, thin=1, verbose=G, 190 | b0=0, B0=1/100, c0=2, d0=2, Time = time.id) 191 | 192 | ## estimated break numbers 193 | ## thresho 194 | estimated.breaks <- make.breaklist(BF, threshold=3) 195 | 196 | ## print all posterior model probabilities 197 | print(attr(BF, "model.prob")) 198 | } 199 | 200 | } 201 | \references{ 202 | Jong Hee Park, 2012. ``Unified Method for Dynamic and 203 | Cross-Sectional Heterogeneity: Introducing Hidden Markov Panel Models.'' 204 | \emph{American Journal of Political Science}.56: 1040-1054. 205 | 206 | 207 | Siddhartha Chib. 1998. ``Estimation and comparison of multiple change-point 208 | models.'' \emph{Journal of Econometrics}. 86: 221-241. 209 | 210 | } 211 | \keyword{models} 212 | -------------------------------------------------------------------------------- /man/tomogplot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/tomog.R 3 | \name{tomogplot} 4 | \alias{tomogplot} 5 | \title{Tomography Plot} 6 | \usage{ 7 | tomogplot( 8 | r0, 9 | r1, 10 | c0, 11 | c1, 12 | xlab = "fraction of r0 in c0 (p0)", 13 | ylab = "fraction of r1 in c0 (p1)", 14 | bgcol = "white", 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{r0}{An \eqn{(ntables \times 1)} vector of row sums from 20 | row 0.} 21 | 22 | \item{r1}{An \eqn{(ntables \times 1)} vector of row sums from 23 | row 1.} 24 | 25 | \item{c0}{An \eqn{(ntables \times 1)} vector of column sums 26 | from column 0.} 27 | 28 | \item{c1}{An \eqn{(ntables \times 1)} vector of column sums 29 | from column 1.} 30 | 31 | \item{xlab}{The x axis label for the plot.} 32 | 33 | \item{ylab}{The y axis label for the plot.} 34 | 35 | \item{bgcol}{The background color for the plot.} 36 | 37 | \item{...}{further arguments to be passed} 38 | } 39 | \description{ 40 | tomogplot is used to produce a tomography plot (see King, 1997) for a series 41 | of partially observed 2 x 2 contingency tables. 42 | } 43 | \details{ 44 | Consider the following partially observed 2 by 2 contingency table: 45 | 46 | \tabular{llll}{ 47 | \tab | \eqn{Y=0} \tab | \eqn{Y=1} \tab | \cr 48 | --------- \tab --------- \tab --------- \tab --------- \cr 49 | \eqn{X=0} \tab | \eqn{Y_0} \tab | \tab | \eqn{r_0} \cr 50 | --------- \tab --------- \tab --------- \tab --------- \cr 51 | \eqn{X=1} \tab | \eqn{Y_1} \tab | \tab | \eqn{r_1} \cr 52 | --------- \tab --------- \tab --------- \tab --------- \cr 53 | \tab | \eqn{c_0} \tab | \eqn{c_1} \tab | \eqn{N} 54 | } 55 | 56 | where \eqn{r_0}, \eqn{r_1}, \eqn{c_0}, \eqn{c_1}, and \eqn{N} are 57 | non-negative integers that are observed. The interior cell entries 58 | are not observed. It is assumed that \eqn{Y_0|r_0 \sim 59 | \mathcal{B}inomial(r_0, p_0)} and \eqn{Y_1|r_1 \sim 60 | \mathcal{B}inomial(r_1, p_1)}. 61 | 62 | This function plots the bounds on the maximum likelihood estimatess for (p0, 63 | p1). 64 | } 65 | \examples{ 66 | 67 | r0 <- rpois(100, 500) 68 | r1 <- rpois(100, 200) 69 | c0 <- rpois(100, 100) 70 | c1 <- (r0 + r1) - c0 71 | tomogplot(r0, r1, c0, c1) 72 | 73 | } 74 | \references{ 75 | Gary King, 1997. \emph{A Solution to the Ecological Inference 76 | Problem}. Princeton: Princeton University Press. 77 | 78 | Jonathan C. Wakefield. 2004. ``Ecological Inference for 2 x 2 Tables.'' 79 | \emph{Journal of the Royal Statistical Society, Series A}. 167(3): 385445. 80 | } 81 | \seealso{ 82 | \code{\link{MCMChierEI}}, \code{\link{MCMCdynamicEI}}, 83 | \code{\link{dtomogplot}} 84 | } 85 | \keyword{hplot} 86 | -------------------------------------------------------------------------------- /man/topmodels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SSVSquantregsummary.R 3 | \name{topmodels} 4 | \alias{topmodels} 5 | \title{Shows an ordered list of the most frequently visited models sampled during 6 | quantile regression stochastic search variable selection (QR-SSVS).} 7 | \usage{ 8 | topmodels(qrssvs, nmodels = 5, abbreviate = FALSE, minlength = 3) 9 | } 10 | \arguments{ 11 | \item{qrssvs}{An object of class \code{qrssvs}. Typically this will be the 12 | \code{gamma} component of the list returned by \code{SSVSquantreg}.} 13 | 14 | \item{nmodels}{The number of models to tabulate.} 15 | 16 | \item{abbreviate}{Logical: should the names of the predictors be 17 | abbreviated?} 18 | 19 | \item{minlength}{If \code{abbreviate} is set to \code{TRUE}, the minimum 20 | length of the abbreviations.} 21 | } 22 | \value{ 23 | A table with the models and their associated posterior probability. 24 | The models are arranged in descending order of probability. 25 | } 26 | \description{ 27 | Given output from quantile regression stochastic search variable selection, 28 | this function returns a table of the 'best' models together with their 29 | associated empirical posterior probability. 30 | } 31 | \examples{ 32 | 33 | \dontrun{ 34 | set.seed(1) 35 | epsilon<-rnorm(100) 36 | set.seed(2) 37 | x<-matrix(rnorm(1000),100,10) 38 | y<-x[,1]+x[,10]+epsilon 39 | qrssvs<-SSVSquantreg(y~x) 40 | topmodels(qrssvs$gamma) 41 | } 42 | 43 | } 44 | \seealso{ 45 | \code{\link[MCMCpack]{SSVSquantreg}} 46 | } 47 | \author{ 48 | Craig Reed 49 | } 50 | \keyword{models} 51 | -------------------------------------------------------------------------------- /man/vech.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utility.R 3 | \name{vech} 4 | \alias{vech} 5 | \title{Extract Lower Triangular Elements from a Symmetric Matrix} 6 | \usage{ 7 | vech(x) 8 | } 9 | \arguments{ 10 | \item{x}{A symmetric matrix.} 11 | } 12 | \value{ 13 | A list of the lower triangular elements. 14 | } 15 | \description{ 16 | This function takes a symmetric matrix and extracts a list of all lower 17 | triangular elements. 18 | } 19 | \details{ 20 | This function checks to make sure the matrix is square, but it does not 21 | check for symmetry (it just pulls the lower triangular elements). The 22 | elements are stored in column major order. The original matrix can be 23 | restored using the \code{xpnd} command. 24 | } 25 | \examples{ 26 | 27 | symmat <- matrix(c(1,2,3,4,2,4,5,6,3,5,7,8,4,6,8,9),4,4) 28 | vech(symmat) 29 | 30 | } 31 | \seealso{ 32 | \code{\link{xpnd}} 33 | } 34 | \keyword{manip} 35 | -------------------------------------------------------------------------------- /man/write.Scythe.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/scythe.R 3 | \name{write.Scythe} 4 | \alias{write.Scythe} 5 | \title{Write a Matrix to a File to be Read by Scythe} 6 | \usage{ 7 | write.Scythe(outmatrix, outfile = NA, overwrite = FALSE) 8 | } 9 | \arguments{ 10 | \item{outmatrix}{The matrix to be written to a file.} 11 | 12 | \item{outfile}{The file to be written. This can include path information.} 13 | 14 | \item{overwrite}{A logical that determines whether an existing file should 15 | be over-written. By default, it protects the user from over-writing 16 | existing files.} 17 | } 18 | \value{ 19 | A zero if the file is properly written. 20 | } 21 | \description{ 22 | This function writes a matrix to an ASCII file that can be read by the 23 | Sycthe Statistical Library. Scythe requires that input files contain the 24 | number of rows and columns in the first row, followed by the data. 25 | } 26 | \examples{ 27 | 28 | \dontrun{ 29 | write.Scythe(mymatrix, file.path(tempdir(), "myfile.txt")) 30 | } 31 | 32 | } 33 | \references{ 34 | Daniel Pemstein, Kevin M. Quinn, and Andrew D. Martin. 2007. 35 | \emph{Scythe Statistical Library 1.0.} \url{http://scythe.wustl.edu.s3-website-us-east-1.amazonaws.com/}. 36 | } 37 | \seealso{ 38 | \code{\link{write.Scythe}} 39 | } 40 | \keyword{file} 41 | -------------------------------------------------------------------------------- /man/xpnd.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utility.R 3 | \name{xpnd} 4 | \alias{xpnd} 5 | \title{Expand a Vector into a Symmetric Matrix} 6 | \usage{ 7 | xpnd(x, nrow = NULL) 8 | } 9 | \arguments{ 10 | \item{x}{A list of elements to expand into symmetric matrix.} 11 | 12 | \item{nrow}{The number of rows (and columns) in the returned matrix. Look 13 | into the details.} 14 | } 15 | \value{ 16 | An \eqn{(nrows \times nrows)} symmetric matrix. 17 | } 18 | \description{ 19 | This function takes a vector of appropriate length (typically created using 20 | \code{vech}) and creates a symmetric matrix. 21 | } 22 | \details{ 23 | This function is particularly useful when dealing with variance covariance 24 | matrices. Note that R stores matrices in column major order, and that the 25 | items in \code{x} will be recycled to fill the matrix if need be. 26 | 27 | The number of rows can be specified or automatically computed from the 28 | number of elements in a given object via \eqn{(-1 + \sqrt{(1 + 8 * 29 | length(x))}) / 2}. 30 | } 31 | \examples{ 32 | 33 | xpnd(c(1,2,3,4,4,5,6,7,8,9),4) 34 | xpnd(c(1,2,3,4,4,5,6,7,8,9)) 35 | 36 | } 37 | \seealso{ 38 | \code{\link{vech}} 39 | } 40 | \keyword{manip} 41 | -------------------------------------------------------------------------------- /src/MCMCmnl.h: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // MCMCmnl.h contains multinomial logit functions called by both the 3 | // metropolis hastings and slice sampling implemenetation of MCMCmnl, 4 | // such as a function that returns the log posterior. 5 | // 6 | // Andrew D. Martin 7 | // Dept. of Political Science 8 | // Washington University in St. Louis 9 | // admartin@wustl.edu 10 | // 11 | // Kevin M. Quinn 12 | // Dept. of Government 13 | // Harvard University 14 | // kevin_quinn@harvard.edu 15 | // 16 | // This software is distributed under the terms of the GNU GENERAL 17 | // PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 18 | // file for more information. 19 | // 20 | // DBP 7/27/2007 21 | // 22 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 23 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 24 | // and Jong Hee Park 25 | ////////////////////////////////////////////////////////////////////////// 26 | 27 | 28 | #ifndef MCMCMNL_H 29 | #define MCMCMNL_H 30 | 31 | #include "matrix.h" 32 | #include "algorithm.h" 33 | #include "distributions.h" 34 | #include "la.h" 35 | #include "smath.h" 36 | 37 | using namespace std; 38 | using namespace scythe; 39 | 40 | inline double 41 | mnl_logpost(const Matrix<>& Y, const Matrix<>& X, const Matrix<>& beta, 42 | const Matrix<>& beta_prior_mean, 43 | const Matrix<>& beta_prior_prec) 44 | { 45 | 46 | // likelihood 47 | double loglike = 0.0; 48 | const Matrix numera = exp(X * beta); 49 | //numer = reshape(numer, Y.rows(), Y.cols()); 50 | //numer.resize(Y.rows(), Y.cols(), true); 51 | Matrix numer(Y.rows(), Y.cols(), false); 52 | copy(numera, numer); 53 | double *denom = new double[Y.rows()]; 54 | for (unsigned int i = 0; i < Y.rows(); ++i) { 55 | denom[i] = 0.0; 56 | for (unsigned int j = 0; j < Y.cols(); ++j) { 57 | if (Y(i,j) != -999){ 58 | denom[i] += numer(i,j); 59 | } 60 | } 61 | for (unsigned int j = 0; j < Y.cols(); ++j) { 62 | if (Y(i,j) == 1.0){ 63 | loglike += std::log(numer(i,j) / denom[i]); 64 | } 65 | } 66 | } 67 | 68 | delete [] denom; 69 | 70 | // prior 71 | // double logprior = 0.0; 72 | //if (beta_prior_prec(0,0) != 0) { 73 | // logprior = lndmvn(beta, beta_prior_mean, invpd(beta_prior_prec)); 74 | // } 75 | // 76 | // the following is only up to proportionality 77 | const double logprior = -0.5 *(t(beta - beta_prior_mean) * 78 | beta_prior_prec * 79 | (beta - beta_prior_mean))(0); 80 | 81 | 82 | 83 | return (loglike + logprior); 84 | } 85 | 86 | #endif 87 | -------------------------------------------------------------------------------- /src/MCMCrng.h: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // MCMCrng.h is the header file for MCMCrng.cc. It contains 3 | // functions used to handle random number generator streams. 4 | // 5 | // Andrew D. Martin 6 | // Dept. of Political Science 7 | // Washington University in St. Louis 8 | // admartin@wustl.edu 9 | // 10 | // Kevin M. Quinn 11 | // Dept. of Government 12 | // Harvard University 13 | // kevin_quinn@harvard.edu 14 | // 15 | // This software is distributed under the terms of the GNU GENERAL 16 | // PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 17 | // file for more information. 18 | // 19 | // ADM 7/22/04 20 | // 21 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 22 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 23 | // and Jong Hee Park 24 | ////////////////////////////////////////////////////////////////////////// 25 | 26 | #ifndef MCMCRNG_H 27 | #define MCMCRNG_H 28 | 29 | #include "mersenne.h" 30 | #include "lecuyer.h" 31 | 32 | /* This allows model handles to efficiently pass the appropriate rng 33 | * to object a model's implementation. The first arg is the name of 34 | * the model implementation function. The remaining arguments are the 35 | * arguments to the model implementation function. 36 | * 37 | * The macro assumes that the function it is called in contains an int 38 | * pointer named uselecuyer holding a boolean indication of whether or 39 | * not to use the lecuyer rng. Secondly, it assumes the function 40 | * contains a pointer to an array of integers called seedarray that 41 | * contains six random number seeds (or just one if using mersenne). 42 | * Finally, it assumes it contains a pointer to an integer called 43 | * lecuyerstream that indicates which of the lecuyer generator's 44 | * streams to use. 45 | */ 46 | 47 | #define MCMCPACK_PASSRNG2MODEL(MODEL_IMPL, ...) \ 48 | { \ 49 | unsigned long u_seed_array[6]; \ 50 | for (int i = 0; i < 6; ++i) \ 51 | u_seed_array[i] = static_cast(seedarray[i]); \ 52 | \ 53 | if (*uselecuyer == 0) { \ 54 | mersenne the_rng; \ 55 | the_rng.initialize(u_seed_array[0]); \ 56 | MODEL_IMPL(the_rng, __VA_ARGS__); \ 57 | } else { \ 58 | lecuyer::SetPackageSeed(u_seed_array); \ 59 | for (int i = 0; i < (*lecuyerstream - 1); ++i) \ 60 | lecuyer skip_rng; \ 61 | lecuyer the_rng; \ 62 | MODEL_IMPL(the_rng, __VA_ARGS__); \ 63 | } \ 64 | } 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /src/Makevars.in: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = -DSCYTHE_COMPILE_DIRECT -DSCYTHE_DEBUG=0 -DSCYTHE_RPACK -DHAVE_TRUNC @MV_HAVE_IEEEFP_H@ @MV_HAVE_TRUNC@ 2 | 3 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = -DSCYTHE_COMPILE_DIRECT -DSCYTHE_DEBUG=0 -DSCYTHE_RPACK -DHAVE_TRUNC -DHAVE_TRUNC 2 | 3 | -------------------------------------------------------------------------------- /src/algorithm.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Scythe Statistical Library 3 | * Copyright (C) 2000-2002 Andrew D. Martin and Kevin M. Quinn; 4 | * 2002-present Andrew D. Martin, Kevin M. Quinn, and Daniel 5 | * Pemstein. All Rights Reserved. 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * under the terms of the GNU General Public License as published by 9 | * Free Software Foundation; either version 2 of the License, or (at 10 | * your option) any later version. See the text files COPYING 11 | * and LICENSE, distributed with this source code, for further 12 | * information. 13 | * -------------------------------------------------------------------- 14 | * scythestat/algorithm.h 15 | */ 16 | 17 | /*! \file algorithm.h 18 | * 19 | * \brief Generic algorithms for Scythe objects. 20 | * 21 | * This file provides implementations of a few algorithms that operate 22 | * on Scythe objects and also contains the definitions of a handful of 23 | * useful function objects. These functions and functors are primarily 24 | * intended for use within the library. We add algorithms to this 25 | * header as need arises and do not currently attempt to provide a 26 | * comprehensive set of generic algorithms for working with Scythe 27 | * matrices. 28 | * 29 | */ 30 | 31 | #ifndef SCYTHE_ALGORITHM_H 32 | #define SCYTHE_ALGORITHM_H 33 | 34 | #include 35 | #include 36 | #include 37 | 38 | #ifdef SCYTHE_COMPILE_DIRECT 39 | #include "defs.h" 40 | #include "matrix.h" 41 | #include "matrix_random_access_iterator.h" 42 | #else 43 | #include "scythestat/defs.h" 44 | #include "scythestat/matrix.h" 45 | #include "scythestat/matrix_random_access_iterator.h" 46 | #endif 47 | 48 | // These are just goofy 49 | 50 | #ifdef SCYTHE_RPACK 51 | #undef DO 52 | #undef DS 53 | #undef SO 54 | #undef SS 55 | #endif 56 | 57 | namespace scythe { 58 | namespace { 59 | typedef unsigned int uint; 60 | } 61 | 62 | /* Matrix forward declaration */ 63 | template 64 | class Matrix; 65 | 66 | /*! \brief A Functor encapsulating exponentiation. 67 | * 68 | * This function object wraps exponentiation operations for use in 69 | * generic algorithms. 70 | */ 71 | template 72 | struct exponentiate 73 | { 74 | T operator() (T base, T exp) const 75 | { 76 | return std::pow(base, exp); 77 | } 78 | }; 79 | 80 | /*! \brief A Functor encapsulating \f$ax+b\f$. 81 | * 82 | * This function object wraps the operation \f$ax+b\f$ for use in 83 | * generic algorithms, where a is some constant. 84 | */ 85 | template 86 | struct ax_plus_b 87 | { 88 | T a_; 89 | ax_plus_b (T a) : a_ (a) {} 90 | T operator() (T x, T b) const 91 | { 92 | return (a_ * x + b); 93 | } 94 | }; 95 | 96 | /*! \brief Iterate through a Matrix in order. 97 | * 98 | * This function iterates through a Matrix, \a M, in order, 99 | * setting each element in the Matrix to the result of an invocation 100 | * of the function object, \a func. The () operator of \a func 101 | * should take two unsigned integer parameters (i - the row offset 102 | * into \a M; j - the column offset into \a M) and return a result 103 | * of type T. 104 | * 105 | * \param M The Matrix to iterate over. 106 | * \param func The functor to execute on each iteration. 107 | * 108 | */ 109 | 110 | template 111 | void 112 | for_each_ij_set (Matrix& M, FUNCTOR func) 113 | { 114 | if (O == Col) { 115 | for (uint j = 0; j < M.cols(); ++j) 116 | for (uint i = 0; i < M.rows(); ++i) 117 | M(i, j) = func(i, j); 118 | } else { 119 | for (uint i = 0; i < M.cols(); ++i) 120 | for (uint j = 0; j < M.rows(); ++j) 121 | M(i, j) = func(i, j); 122 | } 123 | } 124 | 125 | /*! \brief Copy the contents of one Matrix into another. 126 | * 127 | * This function copies the contents of one Matrix into 128 | * another, traversing each Matrix in the order specified by the 129 | * template terms ORDER1 and ORDER2. This function requires an 130 | * explicit template call that specifies ORDER1 and ORDER2. 131 | * 132 | * \param source The Matrix to copy. 133 | * \param dest The Matrix to copy into. 134 | */ 135 | 136 | template 139 | void 140 | copy(const Matrix& source, Matrix& dest) 141 | { 142 | std::copy(source.template begin_f(), 143 | source.template end_f(), 144 | dest.template begin_f()); 145 | } 146 | 147 | /*! \brief Copy the contents of one Matrix into another. 148 | * 149 | * This function copies the contents of one Matrix into 150 | * another, traversing each Matrix in the order specified by the 151 | * template terms ORDER1 and ORDER2. If \a source is larger than \a 152 | * dest, the function only copies as many elements from \a source as 153 | * will fit in \a dest. On the other hand, if \a source is smaller 154 | * than \a dest, the function will start over at the beginning of 155 | * \a source, recycling the contents of \a source as many times as 156 | * necessary to fill \a dest. This function requires an explicit 157 | * template call that specifies ORDER1 and ORDER2. 158 | * 159 | * \param source The Matrix to copy. 160 | * \param dest The Matrix to copy into. 161 | */ 162 | template 165 | void 166 | copy_recycle (const Matrix& source, Matrix& dest) 167 | { 168 | if (source.size() == dest.size()) { 169 | copy (source, dest); 170 | } else if (source.size() > dest.size()) { 171 | const_matrix_random_access_iterator s_iter 172 | = source.template begin(); 173 | std::copy(s_iter, s_iter + dest.size(), 174 | dest.template begin_f()); 175 | } else { 176 | const_matrix_random_access_iterator s_begin 177 | = source.template begin (); 178 | matrix_random_access_iterator d_iter 179 | = dest.template begin(); 180 | matrix_random_access_iterator d_end 181 | = dest.template end(); 182 | while (d_iter != d_end) { 183 | unsigned int span = std::min(source.size(), 184 | (unsigned int) (d_end - d_iter)); 185 | d_iter = std::copy(s_begin, s_begin + span, d_iter); 186 | } 187 | } 188 | } 189 | 190 | /*! \brief Determine the sign of a number. 191 | * 192 | * This function compares \a x to (T) 0, returning (T) 1 if \a x is 193 | * greater than zero, (T) -1 if \a x is less than zero, and (T) 0 194 | * otherwise. 195 | * 196 | * \param x The value to check. 197 | */ 198 | template 199 | inline T sgn (const T & x) 200 | { 201 | if (x > (T) 0) 202 | return (T) 1; 203 | else if (x < (T) 0) 204 | return (T) -1; 205 | else 206 | return (T) 0; 207 | } 208 | 209 | } // end namespace scythe 210 | 211 | #endif /* SCYTHE_ALGORITHM_H */ 212 | -------------------------------------------------------------------------------- /src/cMCMCirt1d.cc: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // cMCMCirt1d.cc is C++ code to estimate a one-dimensional item response 3 | // theory model. 4 | // 5 | // ADM and KQ 1/15/2003 6 | // ADM 7/28/2004 [updated to new Scythe version] 7 | // completely rewritten and optimized for the 1-d case 8/2/2004 KQ 8 | // storage changed to save memory KQ 1/27/2006 9 | // DBP 7/3/07 [ported to scythe 1.0.x] 10 | // 11 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 12 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 13 | // and Jong Hee Park 14 | ////////////////////////////////////////////////////////////////////////// 15 | 16 | #ifndef CMCMCIRT1D_CC 17 | #define CMCMCIRT1D_CC 18 | 19 | #include "MCMCrng.h" 20 | #include "MCMCfcds.h" 21 | #include "matrix.h" 22 | #include "distributions.h" 23 | #include "stat.h" 24 | #include "la.h" 25 | #include "ide.h" 26 | #include "smath.h" 27 | #include "rng.h" 28 | #include "mersenne.h" 29 | #include "lecuyer.h" 30 | 31 | #include // needed to use Rprintf() 32 | #include // needed to allow user interrupts 33 | 34 | using namespace std; 35 | using namespace scythe; 36 | 37 | /* cMCMCirt1d implementation. */ 38 | template 39 | void MCMCirt1d_impl (rng& stream, const Matrix& X, 40 | Matrix<>& theta, Matrix<>& eta, const Matrix<>& ab0, 41 | const Matrix<>& AB0, const Matrix<>& theta_eq, 42 | const Matrix<>& theta_ineq, double t0, double T0, unsigned int burnin, 43 | unsigned int mcmc, unsigned int thin, unsigned int verbose, 44 | bool storea, bool storei, double* sampledata, unsigned int samplesize) 45 | { 46 | // constants 47 | const unsigned int J = X.rows(); // # subjects (justices, legislators) 48 | const unsigned int K = X.cols(); // number of items (cases, roll calls) 49 | const unsigned int tot_iter = burnin + mcmc; 50 | const unsigned int nsamp = mcmc / thin; 51 | 52 | // storage matrices (col major order) 53 | Matrix<> theta_store; 54 | Matrix<> eta_store; 55 | if (storea) 56 | theta_store = Matrix<>(nsamp, J); 57 | 58 | if (storei) 59 | eta_store = Matrix<>(nsamp, K*2); 60 | 61 | // starting values 62 | Matrix<> Z(J, K); 63 | 64 | // pre-compute 65 | const Matrix<> AB0ab0 = AB0 * ab0; 66 | 67 | unsigned int count = 0; 68 | // MCMC sampling occurs in this for loop 69 | for (unsigned int iter = 0; iter < tot_iter; ++iter){ 70 | 71 | // sample latent utilities (Z) 72 | irt_Z_update1(Z, X, theta, eta, stream); 73 | 74 | // sample item (case, bill) parameters (eta) 75 | irt_eta_update1(eta, Z, theta, AB0, AB0ab0, stream); 76 | 77 | // sample ability (ideal points) (theta) 78 | irt_theta_update1(theta, Z, eta, t0, T0, theta_eq, theta_ineq, stream); 79 | 80 | // print results to screen 81 | if (verbose > 0 && iter % verbose == 0) { 82 | Rprintf("\n\nMCMCirt1d iteration %i of %i \n", (iter+1), tot_iter); 83 | //Rprintf("theta = \n"); 84 | //for (int j=0; j= burnin) && ((iter % thin == 0))) { 90 | 91 | // store ideal points 92 | if (storea) 93 | theta_store(count, _) = theta; 94 | 95 | // store bill parameters 96 | if (storei) 97 | eta_store(count, _) = t(eta); 98 | count++; 99 | } 100 | 101 | R_CheckUserInterrupt(); // allow user interrupts 102 | 103 | } // end Gibbs loop 104 | 105 | // return output 106 | Matrix<> output; 107 | if(! storei && storea) { 108 | output = theta_store; 109 | } else if (storei && ! storea){ 110 | output = eta_store; 111 | } else { 112 | output = cbind(theta_store, eta_store); 113 | } 114 | 115 | for (unsigned int i = 0; i < samplesize; ++i) 116 | sampledata[i] = output[i]; 117 | 118 | } 119 | 120 | extern "C" { 121 | 122 | void 123 | cMCMCirt1d(double* sampledata, const int* samplerow, const int* samplecol, 124 | const int* Xdata, const int* Xrow, const int* Xcol, 125 | const int* burnin, const int* mcmc, const int* thin, 126 | const int *uselecuyer, const int *seedarray, 127 | const int *lecuyerstream, 128 | const int* verbose, const double* thetastartdata, 129 | const int* thetastartrow, const int* thetastartcol, 130 | const double* astartdata, const int* astartrow, const int* astartcol, 131 | const double* bstartdata, const int* bstartrow, const int* bstartcol, 132 | const double* t0, const double* T0, const double* ab0data, 133 | const int* ab0row, const int* ab0col, const double* AB0data, 134 | const int* AB0row, const int* AB0col, const double* thetaeqdata, 135 | const int* thetaeqrow, const int* thetaeqcol, 136 | const double* thetaineqdata, const int* thetaineqrow, 137 | const int* thetaineqcol, const int* storei, const int* storea) 138 | { 139 | // put together matrices 140 | const Matrix X(*Xrow, *Xcol, Xdata); 141 | Matrix<> theta(*thetastartrow, *thetastartcol, thetastartdata); 142 | Matrix<> alpha(*astartrow, *astartcol, astartdata); 143 | Matrix<> beta(*bstartrow, *bstartcol, bstartdata); 144 | const Matrix<> ab0(*ab0row, *ab0col, ab0data); 145 | const Matrix<> AB0(*AB0row, *AB0col, AB0data); 146 | const Matrix<> theta_eq(*thetaeqrow, *thetaeqcol, thetaeqdata); 147 | const Matrix<> theta_ineq(*thetaineqrow, *thetaineqcol, thetaineqdata); 148 | Matrix<> eta = cbind(alpha, beta); 149 | const int samplesize = (*samplerow) * (*samplecol); 150 | 151 | MCMCPACK_PASSRNG2MODEL(MCMCirt1d_impl, X, theta, eta, ab0, 152 | AB0, theta_eq, theta_ineq, *t0, *T0, *burnin, *mcmc, *thin, 153 | *verbose, *storea, *storei, sampledata, samplesize); 154 | } 155 | } 156 | 157 | #endif 158 | -------------------------------------------------------------------------------- /src/cMCMClogit.cc: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // cMCMClogit.cc is C++ code to estimate a logistic regression model with 3 | // a multivariate normal prior 4 | // 5 | // Andrew D. Martin 6 | // Dept. of Political Science 7 | // Washington University in St. Louis 8 | // admartin@wustl.edu 9 | // 10 | // Kevin M. Quinn 11 | // Dept. of Government 12 | // Harvard University 13 | // kevin_quinn@harvard.edu 14 | // 15 | // This software is distributed under the terms of the GNU GENERAL 16 | // PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 17 | // file for more information. 18 | // 19 | // updated to the new version of Scythe 7/25/2004 KQ 20 | // 21 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 22 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 23 | // and Jong Hee Park 24 | ////////////////////////////////////////////////////////////////////////// 25 | 26 | 27 | #ifndef CMCMCLOGIT_CC 28 | #define CMCMCLOGIT_CC 29 | 30 | #include 31 | #include "MCMCrng.h" 32 | #include "MCMCfcds.h" 33 | #include "matrix.h" 34 | #include "distributions.h" 35 | #include "stat.h" 36 | #include "la.h" 37 | #include "ide.h" 38 | #include "smath.h" 39 | 40 | #include // needed to use Rprintf() 41 | #include // needed to allow user interrupts 42 | 43 | using namespace scythe; 44 | using namespace std; 45 | 46 | static double 47 | logit_logpost(const Matrix<>& Y, const Matrix<>& X, const Matrix<>& beta, 48 | const Matrix<>& beta_prior_mean, 49 | const Matrix<>& beta_prior_prec) 50 | { 51 | // likelihood 52 | const Matrix<> eta = X * beta; 53 | const Matrix<> p = 1.0 / (1.0 + exp(-eta)); 54 | double loglike = 0.0; 55 | 56 | for (unsigned int i = 0; i < Y.rows(); ++ i) 57 | loglike += Y(i) * ::log(p(i)) + (1 - Y(i)) * ::log(1 - p(i)); 58 | 59 | //prior 60 | double logprior = 0.0; 61 | if (beta_prior_prec(0) != 0) 62 | logprior = lndmvn(beta, beta_prior_mean, invpd(beta_prior_prec)); 63 | 64 | return (loglike + logprior); 65 | } 66 | 67 | template 68 | void 69 | MCMClogit_impl (rng& stream, const Matrix<>& Y, 70 | const Matrix<>& X, const Matrix<>& tune, Matrix<>& beta, 71 | const Matrix<>& b0, const Matrix<>& B0, 72 | const Matrix<>& V, unsigned int burnin, unsigned int mcmc, 73 | unsigned int thin, unsigned int verbose, 74 | Matrix<>& result) 75 | { 76 | 77 | // define constants 78 | const unsigned int tot_iter = burnin + mcmc; // total mcmc iterations 79 | const unsigned int k = X.cols(); 80 | 81 | // proposal parameters 82 | const Matrix<> propV = tune * invpd(B0 + invpd(V)) * tune; 83 | const Matrix<> propC = cholesky(propV) ; 84 | 85 | double logpost_cur = logit_logpost(Y, X, beta, b0, B0); 86 | 87 | // MCMC loop 88 | unsigned int count = 0; 89 | unsigned int accepts = 0; 90 | for (unsigned int iter = 0; iter < tot_iter; ++iter) { 91 | 92 | // sample beta 93 | const Matrix<> beta_can = gaxpy(propC, stream.rnorm(k, 1, 0, 1), beta); 94 | 95 | const double logpost_can = logit_logpost(Y, X, beta_can, b0, B0); 96 | const double ratio = ::exp(logpost_can - logpost_cur); 97 | 98 | if (stream.runif() < ratio) { 99 | beta = beta_can; 100 | logpost_cur = logpost_can; 101 | ++accepts; 102 | } 103 | 104 | // store values in matrices 105 | if (iter >= burnin && ((iter % thin) == 0)) { 106 | result(count++, _) = beta; 107 | } 108 | 109 | // print output to stdout 110 | if(verbose > 0 && iter % verbose == 0){ 111 | Rprintf("\n\nMCMClogit iteration %i of %i \n", (iter+1), tot_iter); 112 | Rprintf("beta = \n"); 113 | for (unsigned int j = 0; j < k; ++j) 114 | Rprintf("%10.5f\n", beta(j)); 115 | Rprintf("Metropolis acceptance rate for beta = %3.5f\n\n", 116 | static_cast(accepts) / static_cast(iter+1)); 117 | } 118 | 119 | R_CheckUserInterrupt(); // allow user interrupts 120 | 121 | }// end MCMC loop 122 | if (verbose > 0){ 123 | Rprintf("\n\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); 124 | Rprintf("The Metropolis acceptance rate for beta was %3.5f", 125 | static_cast(accepts) / static_cast(tot_iter)); 126 | Rprintf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); 127 | } 128 | } 129 | 130 | extern "C"{ 131 | 132 | void cMCMClogit(double *sampledata, const int *samplerow, 133 | const int *samplecol, const double *Ydata, 134 | const int *Yrow, const int *Ycol, const double *Xdata, 135 | const int *Xrow, const int *Xcol, const int *burnin, 136 | const int *mcmc, const int *thin, const double *tunedata, 137 | const int *tunerow, const int *tunecol, 138 | const int *uselecuyer, const int *seedarray, 139 | const int *lecuyerstream, const int *verbose, 140 | const double *betastartdata, const int *betastartrow, 141 | const int *betastartcol, const double *b0data, 142 | const int *b0row, const int *b0col, const double *B0data, 143 | const int *B0row, const int *B0col, const double *Vdata, 144 | const int *Vrow, const int *Vcol) 145 | { 146 | 147 | // pull together Matrix objects 148 | Matrix<> Y(*Yrow, *Ycol, Ydata); 149 | Matrix<> X(*Xrow, *Xcol, Xdata); 150 | Matrix<> tune(*tunerow, *tunecol, tunedata); 151 | Matrix<> beta(*betastartrow, *betastartcol, betastartdata); 152 | Matrix<> b0(*b0row, *b0col, b0data); 153 | Matrix<> B0(*B0row, *B0col, B0data); 154 | Matrix<> V(*Vrow, *Vcol, Vdata); 155 | 156 | Matrix<> result(*samplerow, *samplecol, false); 157 | MCMCPACK_PASSRNG2MODEL(MCMClogit_impl, Y, X, tune, beta, b0, B0, V, 158 | *burnin, *mcmc, *thin, *verbose, result); 159 | 160 | unsigned int size = *samplecol * *samplerow; 161 | for (unsigned int i = 0; i < size; ++i) 162 | sampledata[i] = result(i); 163 | } 164 | } 165 | 166 | #endif 167 | -------------------------------------------------------------------------------- /src/cMCMCpoisson.cc: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // cMCMCpoisson.cc is C++ code to estimate a Poisson regression model with 3 | // a multivariate normal prior 4 | // 5 | // Andrew D. Martin 6 | // Dept. of Political Science 7 | // Washington University in St. Louis 8 | // admartin@wustl.edu 9 | // 10 | // Kevin M. Quinn 11 | // Dept. of Government 12 | // Harvard University 13 | // kevin_quinn@harvard.edu 14 | // 15 | // This software is distributed under the terms of the GNU GENERAL 16 | // PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 17 | // file for more information. 18 | // 19 | // updated to the new version of Scythe 7/26/2004 KQ 20 | // updated to Scythe 1.0.X 7/7/2007 ADM 21 | // 22 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 23 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 24 | // and Jong Hee Park 25 | ////////////////////////////////////////////////////////////////////////// 26 | 27 | 28 | #ifndef CMCMCPOISSON_CC 29 | #define CMCMCPOISSON_CC 30 | 31 | #include "MCMCrng.h" 32 | #include "MCMCfcds.h" 33 | #include "matrix.h" 34 | #include "distributions.h" 35 | #include "stat.h" 36 | #include "la.h" 37 | #include "ide.h" 38 | #include "smath.h" 39 | #include "rng.h" 40 | #include "mersenne.h" 41 | #include "lecuyer.h" 42 | 43 | #include // needed to use Rprintf() 44 | #include // needed to allow user interrupts 45 | 46 | using namespace std; 47 | using namespace scythe; 48 | 49 | static double poisson_logpost(const Matrix<>& Y, 50 | const Matrix<>& X, 51 | const Matrix<>& beta, 52 | const Matrix<>& beta_prior_mean, 53 | const Matrix<>& beta_prior_prec){ 54 | 55 | // likelihood 56 | const Matrix<> eta = X * beta; 57 | const Matrix<> mu = exp(eta); 58 | double loglike = 0.0; 59 | for (unsigned int i=0; i reference and fills with the 73 | * posterior. 74 | */ 75 | template 76 | void MCMCpoisson_impl (rng& stream, const Matrix<>& Y, 77 | const Matrix<>& X, const Matrix<>& tune, Matrix<>& beta, const Matrix<>& b0, 78 | const Matrix<>& B0, const Matrix<>& V, unsigned int burnin, 79 | unsigned int mcmc, unsigned int thin, unsigned int verbose, Matrix<>& result) { 80 | 81 | // define constants 82 | const unsigned int tot_iter = burnin + mcmc; // total number iterations 83 | const unsigned int nstore = mcmc / thin; // number of draws to store 84 | const unsigned int k = X.cols(); 85 | 86 | // storage matrix or matrices 87 | Matrix<> storemat(nstore, k); 88 | 89 | // proposal parameters 90 | const Matrix<> propV = tune * invpd(B0 + invpd(V)) * tune; 91 | const Matrix<> propC = cholesky(propV) ; 92 | 93 | double logpost_cur = poisson_logpost(Y, X, beta, b0, B0); 94 | 95 | // MCMC loop 96 | int count = 0; 97 | int accepts = 0; 98 | for (unsigned int iter = 0; iter < tot_iter; ++iter){ 99 | 100 | // sample beta 101 | const Matrix<> beta_can = gaxpy(propC, stream.rnorm(k,1,0,1), beta); 102 | const double logpost_can = poisson_logpost(Y,X,beta_can, b0, B0); 103 | const double ratio = ::exp(logpost_can - logpost_cur); 104 | 105 | if (stream.runif() < ratio){ 106 | beta = beta_can; 107 | logpost_cur = logpost_can; 108 | ++accepts; 109 | } 110 | 111 | // store values in matrices 112 | if (iter >= burnin && (iter % thin==0)){ 113 | storemat(count,_) = beta; 114 | ++count; 115 | } 116 | 117 | // print output to stdout 118 | if(verbose > 0 && iter % verbose == 0){ 119 | Rprintf("\n\nMCMCpoisson iteration %i of %i \n", (iter+1), tot_iter); 120 | Rprintf("beta = \n"); 121 | for (unsigned int j=0; j(accepts) / 125 | static_cast(iter+1)); 126 | } 127 | 128 | R_CheckUserInterrupt(); // allow user interrupts 129 | }// end MCMC loop 130 | 131 | result = storemat; 132 | if (verbose > 0){ 133 | Rprintf("\n\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); 134 | Rprintf("The Metropolis acceptance rate for beta was %3.5f", 135 | static_cast(accepts) / static_cast(tot_iter)); 136 | Rprintf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); 137 | } 138 | } 139 | extern "C"{ 140 | void cMCMCpoisson(double *sampledata, const int *samplerow, 141 | const int *samplecol, const double *Ydata, 142 | const int *Yrow, const int *Ycol, const double *Xdata, 143 | const int *Xrow, const int *Xcol, const int *burnin, 144 | const int *mcmc, const int *thin, const double *tunedata, 145 | const int *tunerow, const int *tunecol, const int *uselecuyer, 146 | const int *seedarray, const int *lecuyerstream, 147 | const int *verbose, const double *betastartdata, 148 | const int *betastartrow, const int *betastartcol, 149 | const double *b0data, const int *b0row, const int *b0col, 150 | const double *B0data, const int *B0row, const int *B0col, 151 | const double *Vdata, const int *Vrow, const int *Vcol) { 152 | 153 | // pull together Matrix objects 154 | const Matrix <> Y(*Yrow, *Ycol, Ydata); 155 | const Matrix <> X(*Xrow, *Xcol, Xdata); 156 | const Matrix <> tune(*tunerow, *tunecol, tunedata); 157 | Matrix <> beta(*betastartrow, *betastartcol, 158 | betastartdata); 159 | const Matrix <> b0(*b0row, *b0col, b0data); 160 | const Matrix <> B0(*B0row, *B0col, B0data); 161 | const Matrix <> V(*Vrow, *Vcol, Vdata); 162 | 163 | Matrix<> storagematrix; 164 | MCMCPACK_PASSRNG2MODEL(MCMCpoisson_impl, Y, X, tune, beta, b0, B0, 165 | V, *burnin, *mcmc, *thin, *verbose, storagematrix); 166 | 167 | const unsigned int size = *samplerow * *samplecol; 168 | for (unsigned int i=0; i // needed to use Rprintf() 43 | #include // needed to allow user interrupts 44 | 45 | using namespace std; 46 | using namespace scythe; 47 | 48 | /* MCMCprobit implementation. Takes Matrix<> reference and fills with the 49 | * posterior. 50 | */ 51 | template 52 | void MCMCprobit_impl (rng& stream, const Matrix<>& Y, 53 | const Matrix<>& X, Matrix<>& beta, const Matrix<>& b0, 54 | const Matrix<>& B0, unsigned int burnin, unsigned int mcmc, 55 | unsigned int thin, unsigned int verbose, bool chib, 56 | Matrix<>& result, 57 | double& logmarglike) { 58 | 59 | // define constants and from cross-product matrices 60 | const unsigned int tot_iter = burnin + mcmc; // total iterations 61 | const unsigned int nstore = mcmc / thin; // number of draws to store 62 | const unsigned int k = X.cols(); 63 | const unsigned int N = X.rows(); 64 | const Matrix<> XpX = crossprod(X); 65 | const Matrix<> B0inv = invpd(B0); 66 | 67 | // storage matrix or matrices 68 | Matrix<> beta_store(nstore, k); 69 | Matrix<> bn_store(nstore, k); 70 | 71 | // initialize Z 72 | Matrix<> Z(N,1); 73 | 74 | // MCMC sampling starts here 75 | unsigned int count = 0; 76 | for (unsigned int iter = 0; iter < tot_iter; ++iter) { 77 | 78 | // [Z| beta, y] 79 | const Matrix<> Z_mean = X * beta; 80 | for (unsigned int i=0; i XpZ = t(X) * Z; 89 | const Matrix Bn = invpd(B0 + XpX); 90 | const Matrix bn = Bn*gaxpy(B0, b0, XpZ); 91 | beta = stream.rmvnorm(bn, Bn); 92 | 93 | // store values in matrices 94 | if (iter >= burnin && (iter % thin==0)){ 95 | beta_store(count,_) = beta; 96 | bn_store(count,_) = bn; 97 | ++count; 98 | } 99 | 100 | // print output to stdout 101 | if(verbose > 0 && iter % verbose == 0){ 102 | Rprintf("\n\nMCMCprobit iteration %i of %i \n", (iter+1), tot_iter); 103 | Rprintf("beta = \n"); 104 | for (unsigned int j=0; j beta_star(k, 1); 115 | beta_star(_ ,0) = meanc(beta_store); 116 | Matrix bn_reduced(k, 1); 117 | Matrix density_beta(nstore, 1); 118 | for (unsigned int iter = 0; iter bn_reduced1 = bn_store(iter, _); 121 | const Matrix Bn = invpd(B0 + XpX); 122 | density_beta(iter) = ::exp(lndmvn(beta_star, bn_reduced, Bn)); 123 | } 124 | double logbeta = log(mean(density_beta)); 125 | 126 | double loglike = 0.0; 127 | Matrix<> eta = X * beta_star; 128 | for (unsigned int i = 0; i < N; ++i) { 129 | double phi = pnorm(eta(i), 0, 1); 130 | loglike += log(dbinom(Y(i), 1, phi)); 131 | } 132 | 133 | // calculate log prior ordinate 134 | double logprior = 0.0; 135 | if (k == 1){ 136 | logprior = log(dnorm(beta_star(0), b0(0), sqrt(B0inv(0)))); 137 | } 138 | else{ 139 | logprior = lndmvn(beta_star, b0, B0inv); 140 | } 141 | // 142 | 143 | logmarglike = loglike + logprior - logbeta; 144 | if (verbose > 0){ 145 | Rprintf("\nlogmarglike = %10.5f\n", logmarglike); 146 | Rprintf("loglike = %10.5f\n", loglike); 147 | Rprintf("log_prior = %10.5f\n", logprior); 148 | Rprintf("log_beta = %10.5f\n", logbeta); 149 | } 150 | }// end of marginal likelihood computation 151 | 152 | result = beta_store; 153 | } 154 | 155 | extern "C"{ 156 | 157 | void cMCMCprobit(double *sampledata, const int *samplerow, 158 | const int *samplecol, const double *Ydata, 159 | const int *Yrow, const int *Ycol, const double *Xdata, 160 | const int *Xrow, const int *Xcol, const int *burnin, 161 | const int *mcmc, const int *thin, const int *uselecuyer, 162 | const int *seedarray, const int *lecuyerstream, 163 | const int *verbose, const double *betastartdata, 164 | const int *betastartrow, const int *betastartcol, 165 | const double *b0data, const int *b0row, const int *b0col, 166 | const double *B0data, const int *B0row, const int *B0col, 167 | double *logmarglikeholder, // double *loglikeholder, 168 | const int *chib) { 169 | 170 | // pull together Matrix objects 171 | const Matrix <> Y(*Yrow, *Ycol, Ydata); 172 | const Matrix <> X(*Xrow, *Xcol, Xdata); 173 | Matrix <> beta (*betastartrow, *betastartcol, 174 | betastartdata); 175 | const Matrix <> b0(*b0row, *b0col, b0data); 176 | const Matrix <> B0(*B0row, *B0col, B0data); 177 | double logmarglike; 178 | // double loglike; 179 | 180 | Matrix<> storagematrix; 181 | MCMCPACK_PASSRNG2MODEL(MCMCprobit_impl, Y, X, beta, b0, B0, *burnin, 182 | *mcmc, *thin, *verbose, *chib, 183 | storagematrix, 184 | logmarglike); 185 | logmarglikeholder[0] = logmarglike; 186 | // loglikeholder[0] = loglike; 187 | 188 | const unsigned int size = *samplerow * *samplecol; 189 | for (unsigned int i=0; i // needed to use Rprintf() 44 | #include // needed to allow user interrupts 45 | 46 | using namespace std; 47 | using namespace scythe; 48 | 49 | /* MCMCprobitres implementation. Takes Matrix<> reference and fills with the 50 | * posterior. 51 | */ 52 | template 53 | void MCMCprobitres_impl (rng& stream, const Matrix<>& Y, 54 | const Matrix<>& X, Matrix<>& beta, 55 | Matrix<>& resvec, 56 | const Matrix<>& b0, 57 | const Matrix<>& B0, unsigned int burnin, 58 | unsigned int mcmc, 59 | unsigned int thin, unsigned int verbose, bool chib, 60 | Matrix<>& result, 61 | double& logmarglike) { 62 | 63 | // define constants and from cross-product matrices 64 | const unsigned int tot_iter = burnin + mcmc; // total number of mcmc iterations 65 | const unsigned int nstore = mcmc / thin; // number of draws to store 66 | const unsigned int k = X.cols(); 67 | const unsigned int N = X.rows(); 68 | const Matrix<> XpX = crossprod(X); 69 | const Matrix<> B0inv = invpd(B0); 70 | 71 | // storage matrix or matrices 72 | Matrix<> beta_store(nstore, k); 73 | Matrix<> Z_store(nstore, N); 74 | 75 | // initialize Z 76 | Matrix<> Z(N,1); 77 | 78 | // MCMC sampling starts here 79 | unsigned int count = 0; 80 | for (unsigned int iter = 0; iter < tot_iter; ++iter){ 81 | 82 | // [Z| beta, y] 83 | const Matrix<> Z_mean = X * beta; 84 | for (unsigned int i=0; i XpZ = t(X) * Z; 93 | beta = NormNormregress_beta_draw(XpX, XpZ, b0, B0, 1.0, stream); 94 | 95 | // store values in matrices 96 | if (iter >= burnin && ((iter % thin)==0)){ 97 | for (unsigned int j = 0; j < k; j++){ 98 | beta_store(count, j) = beta[j]; 99 | } 100 | Z_store(count,_) = Z; 101 | for (unsigned int j=0; j<(resvec.rows()); ++j){ 102 | const int i = static_cast(resvec[j]) - 1; 103 | beta_store(count, j+k) = Z[i] - Z_mean[i]; 104 | } 105 | ++count; 106 | } 107 | 108 | // print output to stdout 109 | if(verbose > 0 && iter % verbose == 0){ 110 | Rprintf("\n\nMCMCprobit iteration %i of %i \n", (iter+1), tot_iter); 111 | Rprintf("beta = \n"); 112 | for (unsigned int j=0; j beta_star = meanc(beta_store); 125 | Matrix density_beta(nstore, 1); 126 | for (unsigned int iter = 0; iter Z_reduced = Z_store(iter,_); 128 | const Matrix XpZ = (::t(X)*Z_reduced); 129 | const Matrix Bn = invpd(B0inv + XpX); 130 | const Matrix bn = Bn*gaxpy(B0inv, b0, XpZ); 131 | density_beta(iter) = exp(lndmvn(beta_star, bn, Bn)); 132 | } 133 | double logbeta = log(prod(meanc(density_beta))); 134 | 135 | double loglike = 0.0; 136 | Matrix<> eta = X * beta_star; 137 | for (unsigned int i = 0; i < X.rows(); ++i) { 138 | double phi = pnorm(eta(i), 0, 1); 139 | loglike += log(dbinom(Y(i), 1, phi)); 140 | } 141 | 142 | // calculate log prior ordinate 143 | double logprior = lndmvn(beta_star, b0, B0inv); 144 | 145 | logmarglike = loglike + logprior - logbeta; 146 | 147 | // Rprintf("\n logmarglike %10.5f", logmarglike, "\n"); 148 | // Rprintf("\n loglike %10.5f", loglike, "\n"); 149 | 150 | }// end of marginal likelihood computation 151 | 152 | result = beta_store; 153 | } 154 | 155 | 156 | 157 | 158 | extern "C"{ 159 | 160 | void MCMCprobitres(double *sampledata, const int *samplerow, 161 | const int *samplecol, const double *Ydata, 162 | const int *Yrow, const int *Ycol, const double *Xdata, 163 | const int *Xrow, const int *Xcol, 164 | const double *resvecdata, const int *resvecrow, 165 | const int *resveccol, const int *burnin, 166 | const int *mcmc, const int *thin, const int *uselecuyer, 167 | const int *seedarray, const int *lecuyerstream, 168 | const int *verbose, const double *betastartdata, 169 | const int *betastartrow, const int *betastartcol, 170 | const double *b0data, const int *b0row, 171 | const int *b0col, const double *B0data, 172 | const int *B0row, const int *B0col, 173 | double *logmarglikeholder, // double *loglikeholder, 174 | const int *chib) { 175 | 176 | 177 | // pull together Matrix objects 178 | const Matrix <> Y(*Yrow, *Ycol, Ydata); 179 | const Matrix <> X(*Xrow, *Xcol, Xdata); 180 | Matrix <> resvec(*resvecrow, *resveccol, 181 | resvecdata); 182 | Matrix <> beta(*betastartrow, *betastartcol, 183 | betastartdata); 184 | const Matrix <> b0(*b0row, *b0col, b0data); 185 | const Matrix <> B0(*B0row, *B0col, B0data); 186 | double logmarglike; 187 | 188 | Matrix<> storagematrix; 189 | MCMCPACK_PASSRNG2MODEL(MCMCprobitres_impl, Y, X, beta, resvec, 190 | b0, B0, *burnin, 191 | *mcmc, *thin, *verbose, *chib, 192 | storagematrix, 193 | logmarglike); 194 | 195 | // return output 196 | const unsigned int size = *samplerow * *samplecol; 197 | for (unsigned int i=0; i // needed to use Rprintf() 51 | #include // needed to allow user interrupts 52 | 53 | using namespace std; 54 | using namespace scythe; 55 | 56 | /* MCMCquantreg implementation. Takes Matrix<> reference which it 57 | * fills with the posterior. 58 | */ 59 | template 60 | void MCMCquantreg_impl (rng& stream, double tau, Matrix<>& Y, 61 | const Matrix<>& X, Matrix<>& beta, const Matrix<>& b0, 62 | const Matrix<>& B0, 63 | unsigned int burnin, unsigned int mcmc, unsigned int thin, 64 | unsigned int verbose, 65 | Matrix<>& result) 66 | { 67 | // define constants 68 | const unsigned int tot_iter = burnin + mcmc; //total iterations 69 | const unsigned int nstore = mcmc / thin; // number of draws to store 70 | const unsigned int k = X.cols (); 71 | 72 | // storage matrices 73 | Matrix<> betamatrix (k, nstore); 74 | 75 | // Gibbs sampler 76 | unsigned int count = 0; 77 | for (unsigned int iter = 0; iter < tot_iter; ++iter) { 78 | Matrix<> e = gaxpy(X, (-1*beta), Y); 79 | Matrix<> abse = fabs(e); 80 | Matrix<> weights = ALaplaceIGaussregress_weights_draw (abse, stream); 81 | beta = ALaplaceNormregress_beta_draw (tau, X, Y, weights, b0, B0, stream); 82 | 83 | // store draws in storage matrix 84 | if (iter >= burnin && (iter % thin == 0)) { 85 | betamatrix(_, count) = beta; 86 | ++count; 87 | } 88 | 89 | // print output to stdout 90 | if(verbose > 0 && iter % verbose == 0) { 91 | Rprintf("\n\nMCMCquantreg iteration %i of %i \n", 92 | (iter+1), tot_iter); 93 | Rprintf("beta = \n"); 94 | for (unsigned int j=0; j Y(*Yrow, *Ycol, Ydata); 120 | Matrix<> X(*Xrow, *Xcol, Xdata); 121 | Matrix<> betastart(*betastartrow, *betastartcol, betastartdata); 122 | Matrix<> b0(*b0row, *b0col, b0data); 123 | Matrix<> B0(*B0row, *B0col, B0data); 124 | 125 | Matrix<> storagematrix; 126 | MCMCPACK_PASSRNG2MODEL(MCMCquantreg_impl, *tau, Y, X, betastart, b0, B0, 127 | *burnin, *mcmc, *thin, *verbose, 128 | storagematrix); 129 | 130 | const unsigned int size = *samplerow * *samplecol; 131 | for (unsigned int i = 0; i < size; ++i) 132 | sampledata[i] = storagematrix(i); 133 | } 134 | } 135 | 136 | #endif 137 | -------------------------------------------------------------------------------- /src/cMCMCtobit.cc: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // cMCMCtobit.cc is a program that simualates draws from the posterior 3 | // density of a linear regression model with Gaussian errors when the 4 | // dependent variable is censored from below and/or above. 5 | // 6 | // The initial version of this file was generated by the 7 | // auto.Scythe.call() function in the MCMCpack R package 8 | // written by: 9 | // 10 | // Andrew D. Martin 11 | // Dept. of Political Science 12 | // Washington University in St. Louis 13 | // admartin@wustl.edu 14 | // 15 | // Kevin M. Quinn 16 | // Dept. of Government 17 | // Harvard University 18 | // kevin_quinn@harvard.edu 19 | // 20 | // This software is distributed under the terms of the GNU GENERAL 21 | // PUBLIC LICENSE Version 2, June 1991. See the package LICENSE 22 | // file for more information. 23 | // 24 | // This file was initially generated on Tue Sep 14 00:50:08 2004 25 | // ADM and KQ 10/10/2002 [ported to Scythe0.3] 26 | // BG 09/18/2004 [updated to new specification, added above censoring] 27 | // ADM 7/7/2007 [updated to Scythe 1.0.X] 28 | // 29 | // Copyright (C) 2003-2007 Andrew D. Martin and Kevin M. Quinn 30 | // Copyright (C) 2007-present Andrew D. Martin, Kevin M. Quinn, 31 | // and Jong Hee Park 32 | ////////////////////////////////////////////////////////////////////////// 33 | 34 | 35 | #ifndef CMCMCTOBIT_CC 36 | #define CMCMCTOBIT_CC 37 | 38 | #include "MCMCrng.h" 39 | #include "MCMCfcds.h" 40 | #include "matrix.h" 41 | #include "distributions.h" 42 | #include "stat.h" 43 | #include "la.h" 44 | #include "ide.h" 45 | #include "smath.h" 46 | #include "rng.h" 47 | #include "mersenne.h" 48 | #include "lecuyer.h" 49 | 50 | #include // needed to use Rprintf() 51 | #include // needed to allow user interrupts 52 | 53 | using namespace std; 54 | using namespace scythe; 55 | 56 | /* MCMCtobit implemenation. Takes Matrix<> reference which it 57 | * fills with the posterior. 58 | */ 59 | template 60 | void MCMCtobit_impl (rng& stream, const Matrix<>& Y, 61 | const Matrix<>& X, Matrix<>& beta, const Matrix<>& b0, 62 | const Matrix<>& B0, double c0, double d0, double below, double above, 63 | unsigned int burnin, unsigned int mcmc, unsigned int thin, 64 | unsigned int verbose, Matrix<>& result) { 65 | 66 | // define constants 67 | const unsigned int tot_iter = burnin + mcmc; // total number of mcmc iterations 68 | const unsigned int nstore = mcmc / thin; // number of draws to store 69 | const unsigned int k = X.cols(); 70 | const unsigned int N = X.rows(); 71 | const Matrix <> XpX = crossprod(X); 72 | 73 | // storage matrix or matrices 74 | Matrix <> betamatrix (k, nstore); 75 | Matrix <> sigmamatrix (1, nstore); 76 | 77 | ///// MCMC SAMPLING OCCURS IN THIS FOR LOOP 78 | int count = 0; 79 | Matrix <> Z = Y; 80 | for(unsigned int iter = 0; iter < tot_iter; ++iter){ 81 | double sigma2 = NormIGregress_sigma2_draw (X, Z, beta, c0, d0, 82 | stream); 83 | Matrix <> Z_mean = X * beta; 84 | 85 | for (unsigned int i=0; i= above) 89 | Z[i] = stream.rtbnorm_combo(Z_mean[i], sigma2, above); 90 | } 91 | Matrix <> XpZ = t(X) * Z; 92 | beta = NormNormregress_beta_draw (XpX, XpZ, b0, B0, sigma2, stream); 93 | 94 | // store draws in storage matrix (or matrices) 95 | if (iter >= burnin && (iter % thin == 0)) { 96 | sigmamatrix (0, count) = sigma2; 97 | betamatrix(_, count) = beta; 98 | ++count; 99 | } 100 | 101 | // print output to stdout 102 | if(verbose > 0 && iter % verbose == 0) { 103 | Rprintf("\n\nMCMCtobit iteration %i of %i \n", 104 | (iter+1), tot_iter); 105 | Rprintf("beta = \n"); 106 | for (unsigned int j=0; j Y(*Yrow, *Ycol, Ydata); 138 | const Matrix <> X(*Xrow, *Xcol, Xdata); 139 | Matrix betastart(*betastartrow, *betastartcol, 140 | betastartdata); 141 | const Matrix <> b0(*b0row, *b0col, b0data); 142 | const Matrix <> B0(*B0row, *B0col, B0data); 143 | 144 | Matrix<> storagematrix; 145 | MCMCPACK_PASSRNG2MODEL(MCMCtobit_impl, Y, X, betastart, b0, B0, 146 | *c0, *d0, *below, *above, *burnin, *mcmc, *thin, *verbose, 147 | storagematrix); 148 | 149 | const unsigned int size = *samplerow * *samplecol; 150 | for (unsigned int i=0; i 60 | class wrapped_generator: public rng > 61 | { 62 | public: 63 | 64 | /*! \brief Default constructor 65 | * 66 | * This constructor wraps the provided random uniform number 67 | * generating function object, creating an object suitable for 68 | * random number generation in Scythe. Note that the function 69 | * object is passed by reference and is not copied on 70 | * construction. 71 | * 72 | * \param e A function object that returns uniform random 73 | * numbers on (0,1) when invoked. 74 | * 75 | * \see wrapped_generator(const wrapped_generator& wg) 76 | */ 77 | wrapped_generator (ENGINE& e) 78 | : rng > (), 79 | engine (e) 80 | {} 81 | 82 | /*! \brief Copy constructor 83 | * 84 | * This constructor makes a copy of an existing 85 | * wrapped_generator object, duplicating its seed and current 86 | * state exactly. Note that this will create a copy of the 87 | * underlying function object using the function objects copy 88 | * construction semantics. 89 | * 90 | * \param wg An existing wrapped_generator object. 91 | * 92 | * \see wrapped_generator(ENGINE& e) 93 | */ 94 | wrapped_generator(const wrapped_generator& wg) 95 | : rng > (), 96 | engine (wg.engine) 97 | {} 98 | 99 | /*! \brief Generate a random uniform variate on (0, 1). 100 | * 101 | * This routine returns a random double precision floating point 102 | * number from the uniform distribution on the interval (0, 103 | * 1). This method overloads the pure virtual method of the 104 | * same name in the rng base class. 105 | * 106 | * \see runif(unsigned int, unsigned int) 107 | * \see rng 108 | */ 109 | inline double runif() 110 | { 111 | return engine(); 112 | } 113 | 114 | /* We have to override the overloaded forms of runif because 115 | * overloading the no-arg runif() hides the base class 116 | * definition; C++ stops looking once it finds the above. 117 | */ 118 | /*! \brief Generate a Matrix of random uniform variates. 119 | * 120 | * This routine returns a Matrix of double precision random 121 | * uniform variates. on the interval (0, 1). This method 122 | * overloads the virtual method of the same name in the rng base 123 | * class. 124 | * 125 | * This is the general template version of this method and 126 | * is called through explicit template instantiation. 127 | * 128 | * \param rows The number of rows in the returned Matrix. 129 | * \param cols The number of columns in the returned Matrix. 130 | * 131 | * \see runif() 132 | * \see rng 133 | * 134 | * \note We are forced to override this overloaded method 135 | * because the 1-arg version of runif() hides the base class's 136 | * definition of this method from the compiler, although it 137 | * probably should not. 138 | */ 139 | template 140 | inline Matrix runif(unsigned int rows, 141 | unsigned int cols) 142 | { 143 | return rng >::runif(rows, cols); 144 | } 145 | 146 | /*! \brief Generate a Matrix of random uniform variates. 147 | * 148 | * This routine returns a Matrix of double precision random 149 | * uniform variates on the interval (0, 1). This method 150 | * overloads the virtual method of the same name in the rng base 151 | * class. 152 | * 153 | * This is the default template version of this method and 154 | * is called through implicit template instantiation. 155 | * 156 | * \param rows The number of rows in the returned Matrix. 157 | * \param cols The number of columns in the returned Matrix. 158 | * 159 | * \see runif() 160 | * \see rng 161 | * 162 | * \note We are forced to override this overloaded method 163 | * because the 1-arg version of runif() hides the base class's 164 | * definition of this method from the compiler, although it 165 | * probably should not. 166 | */ 167 | Matrix runif (unsigned int rows, 168 | unsigned int cols) 169 | { 170 | return rng >::runif(rows, 171 | cols); 172 | } 173 | 174 | protected: 175 | ENGINE& engine; // The wrapped runif engine 176 | }; 177 | } // end namespace scythe 178 | 179 | #endif /* SCYTHE_WRAPPED_GENERATOR_H */ 180 | --------------------------------------------------------------------------------