The R2WinBUGS Package September 13, 2007 Title Running WinBUGS and OpenBUGS from R / S-PLUS Date 2007-09-12 Version 2.1-6 Author originally written by Andrew Gelman <[email protected]>; changes and packaged by Sibylle Sturtz <[email protected]> and Uwe Ligges <[email protected]>. With considerable contributions by Gregor Gorjanc <[email protected]> and Jouni Kerman <[email protected]>. Ported to S-PLUS by Insightful Corp. Description Using this package, it is possible to call a BUGS model, summarize inferences and convergence in a table and graph, and save the simulations in arrays for easy access in R / S-PLUS. In S-PLUS, the openbugs functionality and the windows emulation functionality is not yet available. Depends R (>= 2.5.0), coda (>= 0.11-0) Suggests BRugs (>= 0.3-2) SystemRequirements WinBUGS 1.4 URL http://www.stat.columbia.edu/~gelman/bugsR/ Maintainer Sibylle Sturtz <[email protected]> License GPL version 2 Dialect R, S-PLUS R topics documented: R2WinBUGS-package ................................... 2 as.bugs.array ........................................ 2 attach.all ........................................... 4 bugs ............................................. 5 bugs.data .......................................... 10 bugs.inits .......................................... 11 1
26
Embed
The R2WinBUGS Package - uni-bayreuth.deftp.uni-bayreuth.de/math/statlib/R/CRAN/doc/packages/R2WinBUGS.pdf · The R2WinBUGS Package September 13, 2007 Title Running WinBUGS and OpenBUGS
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
The R2WinBUGS PackageSeptember 13 2007
Title Running WinBUGS and OpenBUGS from R S-PLUS
Date 2007-09-12
Version 21-6
Author originally written by Andrew Gelman ltgelmanstatcolumbiaedugt changes and packagedby Sibylle Sturtz ltsturtzstatistikuni-dortmunddegt and Uwe Liggesltliggesstatistikuni-dortmunddegt With considerable contributions by Gregor Gorjancltgregorgorjancbfrouni-ljsigt and Jouni Kerman ltkermanstatcolumbiaedugt Ported toS-PLUS by Insightful Corp
Description Using this package it is possible to call a BUGS model summarize inferences andconvergence in a table and graph and save the simulations in arrays for easy access in R S-PLUS In S-PLUS the openbugs functionality and the windows emulation functionality is notyet available
R2WinBUGS-package Running WinBUGS and OpenBUGS from R S-PLUS
Description
R2WinBUGS package provides possiblity to call a BUGS model summarize inferences and con-vergence in a table and graph and save the simulations in arrays for easy access in R S-PLUS InS-PLUS the OpenBUGS functionality and the windows emulation functionality is not yet avail-able The main command is bugs
Details
The following are sources of information on R2WinBUGS package
DESCRIPTION file library(help=R2WinBUGS)
This file packageR2WinBUGS
Vignette vignette(R2WinBUGS)
Some help files bugswritemodelprintbugsplotbugs
News fileshow(systemfile(NEWS package=R2WinBUGS))
asbugsarray 3
asbugsarray Convert to bugs object
Description
Function converting results from Markov chain simulations that might not be from BUGS to bugsobject Used mainly to display results with plotbugs
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
modelfile file containing the model written in WinBUGS code
program the program used
DIC logical whether DIC should be calculated see also argument DICOutput anddetails
DICOutput DIC value
niter number of total iterations per chain used for generating simsarray
nburnin length of burn in ie number of iterations to discarded at the beginning forgenerating simsarray
nthin thinning rate a positive integer used for generating simsarray
Details
This function takes a 3-way array of simulations and makes it into a bugs object that can beconveniently displayed using print and plot and accessed using attachbugs If the thirddimension of sims() has names the resulting bugs object will respect that naming conventionFor example if the parameter names are ldquoalpha[1]rdquo ldquoalpha[2]rdquo ldquoalpha[8]rdquo ldquomurdquo ldquotaurdquo thenasbugsarray will know that alpha is a vector of length 8 and mu and tau are scalar parame-ters These will all be plotted appropriately by plot and attached appropriately by attachbugs
If DIC=TRUE then DIC can be either already passed to argument DICOutput as it is done inopenbugs or calculated from deviance values in simsarray
Value
A bugs object is returned
Author(s)
Jouni Kerman 〈kermanstatcolumbiaedu〉 with modification by Andrew Gelman 〈gelmanstatcolumbiaedu〉packaged by Uwe Ligges 〈liggesstatistikuni-dortmundde〉
4 attachall
See Also
bugs
attachall Attach detach elements of (bugs) objects to search path
Description
The database is attacheddetached to the search path See attach for details
Usage
attachall(x overwrite = NA name = attachall)attachbugs(x overwrite = NA)detachall(name = attachall)detachbugs()
Arguments
x An object which must be of class bugs for attachbugs
overwrite If TRUE objects with identical names in the Workspace (GlobalEnv) that aremasking objects in the database to be attached will be deleted If NA (the default)and an interactive session is running a dialog box asks the user whether maskingobjects should be deleted In non-interactive mode behaviour is identical tooverwrite=FALSE ie nothing will be deleted
name The name of the environment where x will be attached which will be detached
Details
While attachall attaches all elements of an object x to a database called name attachbugsattaches all elements of x$simslist to the database bugssims itself making use of attachall
detachall and detachbugs are removing the databases mentioned aboveattachall also attaches nsims (the number of simulations saved from the MCMC runs) tothe database
Each scalar parameter in the model is attached as vectors of length nsims each vector is attachedas a 2-way array (with first dimension equal to nsims) each matrix is attached as a 3-way arrayand so forth
Value
attachall and attachbugs invisibly return the environment(s)
detachall and detachbugs detach the environment(s) named name created by attachall
bugs 5
Note
Without detaching do not use attachall or attachbugs on another (bugs) object be-cause instead of the given name an object called name is attached Therefore strange things mayhappen
See Also
bugs attach detach
Examples
An example model file is given inmodelfile lt- filepath(pathpackage(R2WinBUGS) model schoolstxt) Some example data (see schools for details)data(schools)J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
parameters lt- c(theta mutheta sigmatheta) Not run You may need to edit bugsdirectory also you need write access in the working directoryschoolssim lt- bugs(data inits parameters modelfile
Do some inferential summariesattachbugs(schoolssim) posterior probability that the coaching program in school A is better than in school Cprint(mean(theta[1] gt theta[3])) 50 and school Cs programprint(quantile(theta[1] - theta[3] c(25 75)))plot(theta[1] theta[3])detachbugs() End(Not run)
bugs Run WinBUGS and OpenBUGS from R or S-PLUS
6 bugs
Description
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
R2WinBUGS-package Running WinBUGS and OpenBUGS from R S-PLUS
Description
R2WinBUGS package provides possiblity to call a BUGS model summarize inferences and con-vergence in a table and graph and save the simulations in arrays for easy access in R S-PLUS InS-PLUS the OpenBUGS functionality and the windows emulation functionality is not yet avail-able The main command is bugs
Details
The following are sources of information on R2WinBUGS package
DESCRIPTION file library(help=R2WinBUGS)
This file packageR2WinBUGS
Vignette vignette(R2WinBUGS)
Some help files bugswritemodelprintbugsplotbugs
News fileshow(systemfile(NEWS package=R2WinBUGS))
asbugsarray 3
asbugsarray Convert to bugs object
Description
Function converting results from Markov chain simulations that might not be from BUGS to bugsobject Used mainly to display results with plotbugs
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
modelfile file containing the model written in WinBUGS code
program the program used
DIC logical whether DIC should be calculated see also argument DICOutput anddetails
DICOutput DIC value
niter number of total iterations per chain used for generating simsarray
nburnin length of burn in ie number of iterations to discarded at the beginning forgenerating simsarray
nthin thinning rate a positive integer used for generating simsarray
Details
This function takes a 3-way array of simulations and makes it into a bugs object that can beconveniently displayed using print and plot and accessed using attachbugs If the thirddimension of sims() has names the resulting bugs object will respect that naming conventionFor example if the parameter names are ldquoalpha[1]rdquo ldquoalpha[2]rdquo ldquoalpha[8]rdquo ldquomurdquo ldquotaurdquo thenasbugsarray will know that alpha is a vector of length 8 and mu and tau are scalar parame-ters These will all be plotted appropriately by plot and attached appropriately by attachbugs
If DIC=TRUE then DIC can be either already passed to argument DICOutput as it is done inopenbugs or calculated from deviance values in simsarray
Value
A bugs object is returned
Author(s)
Jouni Kerman 〈kermanstatcolumbiaedu〉 with modification by Andrew Gelman 〈gelmanstatcolumbiaedu〉packaged by Uwe Ligges 〈liggesstatistikuni-dortmundde〉
4 attachall
See Also
bugs
attachall Attach detach elements of (bugs) objects to search path
Description
The database is attacheddetached to the search path See attach for details
Usage
attachall(x overwrite = NA name = attachall)attachbugs(x overwrite = NA)detachall(name = attachall)detachbugs()
Arguments
x An object which must be of class bugs for attachbugs
overwrite If TRUE objects with identical names in the Workspace (GlobalEnv) that aremasking objects in the database to be attached will be deleted If NA (the default)and an interactive session is running a dialog box asks the user whether maskingobjects should be deleted In non-interactive mode behaviour is identical tooverwrite=FALSE ie nothing will be deleted
name The name of the environment where x will be attached which will be detached
Details
While attachall attaches all elements of an object x to a database called name attachbugsattaches all elements of x$simslist to the database bugssims itself making use of attachall
detachall and detachbugs are removing the databases mentioned aboveattachall also attaches nsims (the number of simulations saved from the MCMC runs) tothe database
Each scalar parameter in the model is attached as vectors of length nsims each vector is attachedas a 2-way array (with first dimension equal to nsims) each matrix is attached as a 3-way arrayand so forth
Value
attachall and attachbugs invisibly return the environment(s)
detachall and detachbugs detach the environment(s) named name created by attachall
bugs 5
Note
Without detaching do not use attachall or attachbugs on another (bugs) object be-cause instead of the given name an object called name is attached Therefore strange things mayhappen
See Also
bugs attach detach
Examples
An example model file is given inmodelfile lt- filepath(pathpackage(R2WinBUGS) model schoolstxt) Some example data (see schools for details)data(schools)J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
parameters lt- c(theta mutheta sigmatheta) Not run You may need to edit bugsdirectory also you need write access in the working directoryschoolssim lt- bugs(data inits parameters modelfile
Do some inferential summariesattachbugs(schoolssim) posterior probability that the coaching program in school A is better than in school Cprint(mean(theta[1] gt theta[3])) 50 and school Cs programprint(quantile(theta[1] - theta[3] c(25 75)))plot(theta[1] theta[3])detachbugs() End(Not run)
bugs Run WinBUGS and OpenBUGS from R or S-PLUS
6 bugs
Description
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
modelfile file containing the model written in WinBUGS code
program the program used
DIC logical whether DIC should be calculated see also argument DICOutput anddetails
DICOutput DIC value
niter number of total iterations per chain used for generating simsarray
nburnin length of burn in ie number of iterations to discarded at the beginning forgenerating simsarray
nthin thinning rate a positive integer used for generating simsarray
Details
This function takes a 3-way array of simulations and makes it into a bugs object that can beconveniently displayed using print and plot and accessed using attachbugs If the thirddimension of sims() has names the resulting bugs object will respect that naming conventionFor example if the parameter names are ldquoalpha[1]rdquo ldquoalpha[2]rdquo ldquoalpha[8]rdquo ldquomurdquo ldquotaurdquo thenasbugsarray will know that alpha is a vector of length 8 and mu and tau are scalar parame-ters These will all be plotted appropriately by plot and attached appropriately by attachbugs
If DIC=TRUE then DIC can be either already passed to argument DICOutput as it is done inopenbugs or calculated from deviance values in simsarray
Value
A bugs object is returned
Author(s)
Jouni Kerman 〈kermanstatcolumbiaedu〉 with modification by Andrew Gelman 〈gelmanstatcolumbiaedu〉packaged by Uwe Ligges 〈liggesstatistikuni-dortmundde〉
4 attachall
See Also
bugs
attachall Attach detach elements of (bugs) objects to search path
Description
The database is attacheddetached to the search path See attach for details
Usage
attachall(x overwrite = NA name = attachall)attachbugs(x overwrite = NA)detachall(name = attachall)detachbugs()
Arguments
x An object which must be of class bugs for attachbugs
overwrite If TRUE objects with identical names in the Workspace (GlobalEnv) that aremasking objects in the database to be attached will be deleted If NA (the default)and an interactive session is running a dialog box asks the user whether maskingobjects should be deleted In non-interactive mode behaviour is identical tooverwrite=FALSE ie nothing will be deleted
name The name of the environment where x will be attached which will be detached
Details
While attachall attaches all elements of an object x to a database called name attachbugsattaches all elements of x$simslist to the database bugssims itself making use of attachall
detachall and detachbugs are removing the databases mentioned aboveattachall also attaches nsims (the number of simulations saved from the MCMC runs) tothe database
Each scalar parameter in the model is attached as vectors of length nsims each vector is attachedas a 2-way array (with first dimension equal to nsims) each matrix is attached as a 3-way arrayand so forth
Value
attachall and attachbugs invisibly return the environment(s)
detachall and detachbugs detach the environment(s) named name created by attachall
bugs 5
Note
Without detaching do not use attachall or attachbugs on another (bugs) object be-cause instead of the given name an object called name is attached Therefore strange things mayhappen
See Also
bugs attach detach
Examples
An example model file is given inmodelfile lt- filepath(pathpackage(R2WinBUGS) model schoolstxt) Some example data (see schools for details)data(schools)J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
parameters lt- c(theta mutheta sigmatheta) Not run You may need to edit bugsdirectory also you need write access in the working directoryschoolssim lt- bugs(data inits parameters modelfile
Do some inferential summariesattachbugs(schoolssim) posterior probability that the coaching program in school A is better than in school Cprint(mean(theta[1] gt theta[3])) 50 and school Cs programprint(quantile(theta[1] - theta[3] c(25 75)))plot(theta[1] theta[3])detachbugs() End(Not run)
bugs Run WinBUGS and OpenBUGS from R or S-PLUS
6 bugs
Description
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
attachall Attach detach elements of (bugs) objects to search path
Description
The database is attacheddetached to the search path See attach for details
Usage
attachall(x overwrite = NA name = attachall)attachbugs(x overwrite = NA)detachall(name = attachall)detachbugs()
Arguments
x An object which must be of class bugs for attachbugs
overwrite If TRUE objects with identical names in the Workspace (GlobalEnv) that aremasking objects in the database to be attached will be deleted If NA (the default)and an interactive session is running a dialog box asks the user whether maskingobjects should be deleted In non-interactive mode behaviour is identical tooverwrite=FALSE ie nothing will be deleted
name The name of the environment where x will be attached which will be detached
Details
While attachall attaches all elements of an object x to a database called name attachbugsattaches all elements of x$simslist to the database bugssims itself making use of attachall
detachall and detachbugs are removing the databases mentioned aboveattachall also attaches nsims (the number of simulations saved from the MCMC runs) tothe database
Each scalar parameter in the model is attached as vectors of length nsims each vector is attachedas a 2-way array (with first dimension equal to nsims) each matrix is attached as a 3-way arrayand so forth
Value
attachall and attachbugs invisibly return the environment(s)
detachall and detachbugs detach the environment(s) named name created by attachall
bugs 5
Note
Without detaching do not use attachall or attachbugs on another (bugs) object be-cause instead of the given name an object called name is attached Therefore strange things mayhappen
See Also
bugs attach detach
Examples
An example model file is given inmodelfile lt- filepath(pathpackage(R2WinBUGS) model schoolstxt) Some example data (see schools for details)data(schools)J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
parameters lt- c(theta mutheta sigmatheta) Not run You may need to edit bugsdirectory also you need write access in the working directoryschoolssim lt- bugs(data inits parameters modelfile
Do some inferential summariesattachbugs(schoolssim) posterior probability that the coaching program in school A is better than in school Cprint(mean(theta[1] gt theta[3])) 50 and school Cs programprint(quantile(theta[1] - theta[3] c(25 75)))plot(theta[1] theta[3])detachbugs() End(Not run)
bugs Run WinBUGS and OpenBUGS from R or S-PLUS
6 bugs
Description
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Without detaching do not use attachall or attachbugs on another (bugs) object be-cause instead of the given name an object called name is attached Therefore strange things mayhappen
See Also
bugs attach detach
Examples
An example model file is given inmodelfile lt- filepath(pathpackage(R2WinBUGS) model schoolstxt) Some example data (see schools for details)data(schools)J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
parameters lt- c(theta mutheta sigmatheta) Not run You may need to edit bugsdirectory also you need write access in the working directoryschoolssim lt- bugs(data inits parameters modelfile
Do some inferential summariesattachbugs(schoolssim) posterior probability that the coaching program in school A is better than in school Cprint(mean(theta[1] gt theta[3])) 50 and school Cs programprint(quantile(theta[1] - theta[3] c(25 75)))plot(theta[1] theta[3])detachbugs() End(Not run)
bugs Run WinBUGS and OpenBUGS from R or S-PLUS
6 bugs
Description
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
The bugs function takes data and starting values as input It automatically writes a WinBUGSscript calls the model and saves the simulations for easy access in R or S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model If data=datatxt it is assumed that data havealready been written to the working directory in a file called lsquodatatxtrsquo eg bythe function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the WinBUGS model or a function creating (possibly random)initial values Alternatively if inits=NULL initial values are generated byWinBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in WinBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If the extension is lsquobugrsquo and program==WinBUGSa copy of the file with extension lsquotxtrsquo will be created in the bugs() call andremoved afterwards Note that similarly named lsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
bin number of iterations between saving of results (ie the coda files are saved aftereach bin iterations) default is to save only at the end
bugs 7
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
debug if FALSE (default) WinBUGS is closed automatically when the script has fin-ished running otherwise WinBUGS remains open for further investigation
DIC logical if TRUE (default) compute deviance pD and DIC This is done inWinBUGS directly using the rule pD = Dbar - Dhat If there are less iter-ations than required for the adaptive phase the rule pD=var(deviance) 2 is used
digits number of significant digits used for WinBUGS input see formatC
codaPkg logical if FALSE (default) a bugs object is returned if TRUE file names ofWinBUGS output are returned for easy access by the coda package throughfunction readbugs (not used if program=OpenBUGS)
bugsdirectorydirectory that contains the WinBUGS executable
program the program to use either winbugsWinBUGS or openbugsOpenBUGSthe latter makes use of function openbugs and requires the CRAN packageBRugs The openbugsOpenBUGS choice is not available in S-PLUS
workingdirectorysets working directory during execution of this function WinBUGSrsquo in- andoutput will be stored in this directory if NULL the current working directory ischosen
clearWD logical indicating whether the files lsquodatatxtrsquo lsquoinits[1nchains]txtrsquo lsquologodcrsquolsquocodaIndextxtrsquo and lsquocoda[1nchains]txtrsquo should be removed after WinBUGShas finished If set to TRUE this argument is only respected if codaPkg=FALSE
useWINE logical attempt to use the Wine emulator to run WinBUGS defaults to FALSEon Windows and TRUE otherwise Not available in S-PLUS
WINE character path to lsquowinersquo binary file it is tried hard to get the information auto-matically if not given
newWINE Use new versions of Wine that have lsquowinepathrsquo utility
WINEPATH character path to lsquowinepathrsquo binary file it is tried hard to get the informationautomatically if not given
Details
To run
1 Write a BUGS model in an ASCII file (hint use writemodel)
2 Go into R S-PLUS
3 Prepare the inputs for the bugs function and run it (see Example section)
4 A WinBUGS window will pop up and R S-PLUS will freeze up The model will now runin WinBUGS It might take awhile You will see things happening in the Log window withinWinBUGS When WinBUGS is done its window will close and R S-PLUS will work again
5 If an error message appears re-run with debug=TRUE
BUGS version support
WinBUGS 14 default
8 bugs
OpenBUGS 2 via argument program=OpenBUGS
Operation system support
MS Windows no problem
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Linux Mac OS X and Unix in general possible with Wine emulation via useWINE=TRUE but only for WinBUGS 14
If useWINE=TRUE is used all paths (such as workingdirectory and modelfile mustbe given in native (Unix) style but workingdirectory can be given in Windows path style(eg ldquocProgram FilesWinBUGS14rdquo) or native (Unix) style (eg ldquopathtowinefolderdosdevicescProgramFilesWinBUGS14rdquo) This is done to achieve greatest portability with default argument value forworkingdirectory
Value
If codaPkg=TRUE the returned values are the names of coda output files written by WinBUGScontaining the Markov Chain Monte Carlo output in the CODA format This is useful for directaccess with readbugs
If codaPkg=FALSE the following values are returned
nchains see Section lsquoArgumentsrsquo
niter see Section lsquoArgumentsrsquo
nburnin see Section lsquoArgumentsrsquo
nthin see Section lsquoArgumentsrsquo
nkeep number of iterations kept per chain (equal to (niter-nburnin) nthin)
nsims number of posterior simulations (equal to nchains nkeep)
simsarray 3-way array of simulation output with dimensions nkeep nchains and lengthof combined parameter vector
simslist list of simulated parameters for each scalar parameter a vector of length nsimsfor each vector parameter a 2-way array of simulations for each matrix parame-ter a 3-way array of simulations etc (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
simsmatrix matrix of simulation output with nchainsnkeep rows and one columnfor each element of each saved parameter (for convenience the nkeepnchainssimulations in simsmatrix and simslist (but NOT simsarray) have been ran-domly permuted)
summary summary statistics and convergence information for each saved parameter
mean a list of the estimated parameter means
sd a list of the estimated parameter standard deviations
median a list of the estimated parameter medians
rootshort names of argument parameterstosave and ldquodeviancerdquo
longshort indexes programming stuffdimensionshort
dimension of indexesshort
bugs 9
indexesshortindexes of rootshort
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
lastvalues list of simulations from the most recent iteration they can be used as startingpoints if you wish to run WinBUGS for further iterations
pD an estimate of the effective number of parameters for calculations see the sec-tion ldquoArgumentsrdquo
DIC mean(deviance) + pD
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
References
Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis 2nd editionCRC Press
Sturtz S Ligges U Gelman A (2005) R2WinBUGS A Package for Running WinBUGS fromR Journal of Statistical Software 12(3) 1-16
See Also
printbugs plotbugs as well as coda and BRugs packages
Examples
An example model file is given inmodelfile lt- systemfile(package=R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Write file lsquodatatxtrsquo for WinBUGS to read - for internal use
Usage
bugsdata(data dir = getwd() digits = 5)
Arguments
data either a named list (names corresponding to variable names in the modelfile)of the data for the WinBUGS model or a vector or list of the names of the dataobjects used by the model
dir the directory to write the file lsquodatatxtrsquo to
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the data file lsquodatatxtrsquo is written
See Also
The main function to be called by the user is bugs
bugsinits 11
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
bugsinits Writing input for WinBUGS - intended for internal use only
Description
Write files lsquoinits1txtrsquo lsquoinits2txtrsquo etc in the working directory for WinBUGS to read - for internaluse
Usage
bugsinits(inits nchains digits)
Arguments
inits a list with nchains elements each element of the list is itself a list of startingvalues for the WinBUGS model or a function creating (possibly random) initialvalues
nchains number of Markov chains
digits number of significant digits used for WinBUGS input see formatC
Value
Nothing but as a side effect the inits files lsquoinitstxtrsquo are written
See Also
The main function to be called by the user is bugs
bugslog Read data from WinBUGS logfile
Description
Read data such as summary statistics and DIC information from the WinBUGS logfile
Usage
bugslog(file)
Arguments
file Location of the WinBUGS logfile
12 bugsplot
Details
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
In later releases of R2WinBUGS this function is considered to read the relevant data from the logfile rather than analysing and calculating the relevant data in R S-PLUS again
Value
A list with components
stats A matrix containing summary statistics for each saved parameter Comparableto the information in the element summary of a bugs object as returned bybugs
DIC A matrix containing the DIC statistics as returned from WinBUGS
See Also
The main function that generates the log file is bugs
bugsplot Plotting summary information - intended for internal use only
Description
Plotting summary information - intended for internal use
sims an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to be passed to low-level plot functions
Details
bugsplotsummary (left hand side of plot) and bugsplotinferences (right hand sideof plot)
Value
Does not return anything but prints and plots as side-effects
bugsrun 13
See Also
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
The main function to be called by the user is plot see plotbugs for details
bugsrun Calling WinBUGS
Description
Updates the lengths of the adaptive phases in the WinBUGS registry (using bugsupdatesettings)calls WinBUGS and runs it with lsquoscripttxtrsquo - intended for internal use
Usage
bugsrun(nburnin bugsdirectoryuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
Arguments
nburnin length of burn in
bugsdirectorydirectory that contains the WinBUGS executable
useWINE as in bugs meta function
WINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but has side effects as documented in bugsupdatesettings and calls WinBUGS
See Also
The main function to be called by the user is bugs
14 bugsscript
bugsscript Writes script for running WinBUGS
Description
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Write file lsquoscripttxtrsquo for WinBUGS to read - intended for internal use
Usage
bugsscript(parameterstosave nchains niter nburnin nthinmodelfile debug=FALSE isinits bin DIC=FALSEuseWINE=Platform$OStype = windows newWINE=TRUE WINEPATH=NULL)
Arguments
parameterstosaveparameters that should be monitored
nchains number of Markov chains
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
modelfile file containing the model written in WinBUGS code
debug if FALSE WinBUGS is closed automatically otherwise WinBUGS remainsopen for further investigation
isinits logical whether initial values are given by the user (TRUE) or have to be gener-ated by WinBUGS
bin number of iterations between saving of results
DIC logical if TRUE compute deviance pD and DIC automatically in WinBUGS
useWINE as in bugs meta function
newWINE as in bugs meta function
WINEPATH as in bugs meta function
Value
Nothing but as a side effect the script file lsquoscripttxtrsquo is written
See Also
The main function to be called by the user is bugs
bugssims 15
bugssims WinBUGS output reader
Description
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Reads simulations from WinBUGS into R or S-PLUS formats them monitors convergence per-forms convergence checks and computes medians and quantiles - intended for internal use
niter number of total iterations (including burn in)
nburnin length of burn in
nthin size of thinning parameter
DIC calculation of DIC
Value
Returns the same values as bugs
See Also
The main function to be called by the user is bugs
bugsupdatesettingsAdjusting WinBUGS registry
Description
Adjusts WinBUGS registry - intended for internal use
Usage
bugsupdatesettings(nburnin bugsdirectory)
16 decodeparametername
Arguments
nburnin length of burn inbugsdirectory
directory that contains the WinBUGS executable
Details
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
Alter the adaptive phases in the WinBUGS updaters (in the lsquoBUGSSystemRsrcRegistryodcrsquofile where BUGS is map of installed WinBUGS) so that all adaptive updating is done during theburnin stage Otherwise WinBUGS will not report results if the burnin is less than a minimumvalue such as 500 or 4000 (depending on the model) Write permission on above mentioned file isneeded for this
Value
Nothing but as a side effect the registry file lsquoBUGSSystemRsrcRegistryodcrsquo is modified
See Also
The main function to be called by the user is bugs
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
a a n m k array m sequences of length n k variables measurednchains number of Markov chainstrans a vector of length k if no transformation or log or logit (If trans is
NULL it will be set to log for parameters that are all-positive and 0 otherwise)keepall if FALSE (default) first half of a will be discardedRupperkeep if FALSE donrsquot return Rupper
Details
See the well documented code for details
Value
for monitor
output list of meansd quantiles (25255075975) Rhat ifnchainsgt1 Rupper if (Rupperkeep == TRUE) ampamp (nchainsgt 1) and neff if nchains gt 1
quantiles emipirical quantiles of simulated sequencesconfshrink estimated potential scale reduction (that would be achieved by continuing sim-
ulations forever) has two components an estimate and an approx 975 upperbound
neff effective sample size mnmin(sigmahat^2B1) This is a crude mea-sure of sample size because it relies on the between variance B which can onlybe estimated with m degrees of freedom
See Also
The main function to be called by the user is bugs
18 openbugs
openbugs Wrapper to run OpenBUGS
Description
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
The openbugs function takes data and starting values as input It automatically calls the packageBRugs and runs something similar to BRugsFit Not available in S-PLUS
data either a named list (names corresponding to variable names in the modelfile)of the data for the OpenBUGS model or a vector or list of the names of the dataobjects used by the model If data = datatxt it is assumed that datahave already been written to the working directory in a file called lsquodatatxtrsquo egby the function bugsdata
inits a list with nchains elements each element of the list is itself a list of start-ing values for the OpenBUGS model or a function creating (possibly random)initial values Alternatively if inits are missing or inits = NULL initialvalues are generated by OpenBUGS
parameterstosavecharacter vector of the names of the parameters to save which should be moni-tored
modelfile file containing the model written in OpenBUGS code The extension can beeither lsquobugrsquo or lsquotxtrsquo If lsquobugrsquo a copy of the file with extension lsquotxtrsquo will becreated in the bugs() call and removed afterwards Note that similarly namedlsquotxtrsquo files will be overwritten
nchains number of Markov chains (default 3)
niter number of total iterations per chain (including burn in default 2000)
nburnin length of burn in ie number of iterations to discard at the beginning Defaultis niter2 that is discarding the first half of the simulations
nthin thinning rate Must be a positive integer Set nthin gt 1 to save memory andcomputation time if niter is large Default is max(1 floor(nchains
(niter-nburnin) 1000)) which will only thin if there are atleast 2000 simulations
DIC logical if TRUE (default) compute deviance pD and DIC This is done inBRugs directly
openbugs 19
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
digits number of significant digits used for OpenBUGS input see formatCbugsdirectory
directory that contains the OpenBUGS executable - currently unusedworkingdirectory
sets working directory during execution of this function WinBUGS in- andoutput will be stored in this directory if NULL the current working directory ischosen
Value
A bugs object
Author(s)
Andrew Gelman 〈gelmanstatcolumbiaedu〉 httpwwwstatcolumbiaedu~gelmanbugsR modifications and packaged by Sibylle Sturtz 〈sturtzstatistikuni-dortmundde〉 andUwe Ligges
See Also
bugs and the BRugs package
Examples
An example model file is given inmodelfile lt- systemfile(package = R2WinBUGS model schoolstxt) Lets take a lookfileshow(modelfile)
Some example data (see schools for details)data(schools)schools
J lt- nrow(schools)y lt- schools$estimatesigmay lt- schools$sddata lt- list (J y sigmay)inits lt- function()
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
S3 method for class bugsplot(x displayparallel = FALSE )
Arguments
x an object of class lsquobugsrsquo see bugs for detailsdisplayparallel
display parallel intervals in both halves of the summary plots this is a convergence-monitoring tool and is not necessary once you have approximate convergence(default is FALSE)
further arguments to plot
See Also
bugs
printbugs Printing a bugs object
Description
Printing a bugs object
Usage
S3 method for class bugsprint(x digitssummary = 1 )
readbugs 21
Arguments
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
x an object of class lsquobugsrsquo see bugs for details
digitssummaryrounding for tabular output on the console (default is to round to 1 decimalplace)
further arguments to print
See Also
bugs
readbugs Read output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format produced by WinBUGSand returns an object of class mcmclist for further output analysis using the coda package
Usage
readbugs(codafiles )
Arguments
codafiles character vector of filenames (eg returned from bugs in call such as bugs(codaPkg=TRUE )) Each of the files contains coda output for onechain produced by WinBUGS the directory name of the corresponding filelsquocodaIndextxtrsquo is extracted from the first element of codafiles
further arguments to be passed to readcoda
See Also
bugs readcoda mcmclist
22 writedatafile
schools 8 schools analysis
Description
8 schools analysis
Usage
data(schools)
Format
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
A data frame with 8 observations on the following 3 variables
school See Source
estimate See Source
sd See Source
Source
Rubin DB (1981) Estimation in Parallel Randomized Experiments Journal of EducationalStatistics 6(4) 377-400
Section 55 of Gelman A Carlin JB Stern HS Rubin DB (2003) Bayesian Data Analysis2nd edition CRC Press
writedatafile Write data for WinBUGS
Description
Write data in files that can be read by WinBUGS - intended for internal use
Usage
writedatafile(datalist towhere fill = TRUE)formatdata(datalist)
Arguments
datalist a list to be written into an appropriate structure
towhere the name of the file which the data are to be written to
fill see cat defaults to TRUE
writemodel 23
Valuedatalisttofile
A structure appropriate to be read in by WinBUGS
See Also
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)
The main function to be called by the user is bugs
writemodel Creating a WinBUGS model file
Description
Convert R S-PLUS function to a WinBUGS model file
Usage
writemodel(model con = modelbug)
Arguments
model R S-PLUS function containing the BUGS model in the BUGS model languagefor minor differences see Section Details
con passed to writeLines which actually writes the model file
Details
BUGS models follow closely S syntax It is teherfore possible to write most BUGS models as Rfunctions
As a difference BUGS syntax allows truncation specification like this dnorm() I()but this is illegal in R and S-PLUS To overcome this incompatibility use dummy operator _before I() dnorm() _ I() The dummy operator _ will be removedbefore the BUGS code is saved
In S-PLUS a warning is generated when the model function is defined if the last statement in themodel is an assignment To avoid this warning add the line invisible() to the end of the modeldefinition This line will be removed before the BUGS code is saved
Value
Nothing but as a side effect the model file is written
Author(s)
original idea by Jouni Kerman modified by Uwe Ligges
See Also
bugs
24 writemodel
Examples
Same schoolsmodel that is used in the examples in bugsschoolsmodel lt- function()
for (j in 1J)y[j] ~ dnorm (theta[j] tauy[j])theta[j] ~ dnorm (mutheta tautheta)tauy[j] lt- pow(sigmay[j] -2)