the r2winbugs package -...
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
Depends R (gt= 250) coda (gt= 011-0)
Suggests BRugs (gt= 03-2)
SystemRequirements WinBUGS 14
URL httpwwwstatcolumbiaedu~gelmanbugsR
Maintainer Sibylle Sturtz ltsturtzstatistikuni-dortmunddegt
License GPL version 2
Dialect R S-PLUS
R topics documentedR2WinBUGS-package 2asbugsarray 2attachall 4bugs 5bugsdata 10bugsinits 11
1
2 R2WinBUGS-package
bugslog 11bugsplot 12bugsrun 13bugsscript 14bugssims 15bugsupdatesettings 15decodeparametername 16monitor 17openbugs 18plotbugs 20printbugs 20readbugs 21schools 22writedatafile 22writemodel 23
Index 25
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
Usage
asbugsarray(simsarray modelfile=NULL program=NULLDIC=FALSE DICOutput=NULL niter=NULL nburnin=0 nthin=1)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
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
nchains = 3 niter = 1000bugsdirectory = cProgram FilesWinBUGS14workingdirectory = NULL)
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
2 R2WinBUGS-package
bugslog 11bugsplot 12bugsrun 13bugsscript 14bugssims 15bugsupdatesettings 15decodeparametername 16monitor 17openbugs 18plotbugs 20printbugs 20readbugs 21schools 22writedatafile 22writemodel 23
Index 25
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
Usage
asbugsarray(simsarray modelfile=NULL program=NULLDIC=FALSE DICOutput=NULL niter=NULL nburnin=0 nthin=1)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
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
nchains = 3 niter = 1000bugsdirectory = cProgram FilesWinBUGS14workingdirectory = NULL)
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
asbugsarray(simsarray modelfile=NULL program=NULLDIC=FALSE DICOutput=NULL niter=NULL nburnin=0 nthin=1)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
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
nchains = 3 niter = 1000bugsdirectory = cProgram FilesWinBUGS14workingdirectory = NULL)
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
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
nchains = 3 niter = 1000bugsdirectory = cProgram FilesWinBUGS14workingdirectory = NULL)
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
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
nchains = 3 niter = 1000bugsdirectory = cProgram FilesWinBUGS14workingdirectory = NULL)
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugs(data inits parameterstosave modelfile=modelbugnchains=3 niter=2000 nburnin=floor(niter2)nthin=max(1 floor(nchains (niter - nburnin)1000))bin=(niter - nburnin) nthindebug=FALSE DIC=TRUE digits=5 codaPkg=FALSEbugsdirectory=cProgram FilesWinBUGS14program=c(WinBUGS OpenBUGS winbugs openbugs)workingdirectory=NULL clearWD=FALSEuseWINE=Platform$OStype = windows WINE=NULLnewWINE=TRUE WINEPATH=NULL)
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 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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100)sigmatheta=runif(1 0 100))
or alternatively something like inits lt- list( list(theta=rnorm(J 0 90) mutheta=rnorm(1 0 90) sigmatheta=runif(1 0 90)) list(theta=rnorm(J 0 100) mutheta=rnorm(1 0 100) sigmatheta=runif(1 0 100))
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
10 bugsdata
list(theta=rnorm(J 0 110) mutheta=rnorm(1 0 110) sigmatheta=runif(1 0 110)))
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
nchains=3 niter=5000bugsdirectory=cProgram FilesWinBUGS14workingdirectory=NULL clearWD=TRUE)
print(schoolssim)plot(schoolssim) End(Not run)
bugsdata Writing input for WinBUGS
Description
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugsplotsummary(sims )bugsplotinferences(sims displayparallel )
Arguments
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
bugssims(parameterstosave nchains niter nburnin nthinDIC = TRUE)
Argumentsparameterstosave
parameters 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
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
decodeparameternameDecodes WinBUGS parameter names
Description
Decodes WinBUGS parameter names (eg beta[314] becomes beta with 2 indexes 3 and14) for use by the bugssims function - intended for internal use
Usage
decodeparametername(a)
Arguments
a one element of the first column of lsquocodaIndextxtrsquo
Value
list with elements
root name of parameter eg beta
dimension number of indexes eg 2
indexes indexes eg 3 and 14
given a == beta[3 14]
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
monitor 17
See Also
The main function to be called by the user is bugs
monitor Special summary statistics
Description
Special summary statistics of the WinBUGS output - intended for internal use
Usage
monitor(a nchains trans = NULL keepall = FALSE Rupperkeep = FALSE)convpar(x nchains Rupperkeep = TRUE)
Arguments
x
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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
Usage
openbugs(data inits parameterstosavemodelfile = modeltxt nchains = 3 niter = 2000nburnin = floor(niter2)nthin = max(1 floor(nchains (niter - nburnin) 1000))DIC = TRUE bugsdirectory = cProgram FilesOpenBUGSworkingdirectory = NULL digits = 5)
Arguments
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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()
list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100)sigmatheta = runif(1 0 100))
or alternatively something like inits lt- list( list(theta = rnorm(J 0 90) mutheta = rnorm(1 0 90) sigmatheta = runif(1 0 90)) list(theta = rnorm(J 0 100) mutheta = rnorm(1 0 100) sigmatheta = runif(1 0 100)) list(theta = rnorm(J 0 110) mutheta = rnorm(1 0 110) sigmatheta = runif(1 0 110)))
parameters lt- c(theta mutheta sigmatheta)
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
20 printbugs
Not run both write access in the working directory and package BRugs requiredschoolssim lt- bugs(data inits parameters modelfile
nchains = 3 niter = 5000program = openbugs workingdirectory = NULL)
print(schoolssim)plot(schoolssim) End(Not run)
plotbugs Plotting a bugs object
Description
Plotting a bugs object
Usage
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
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)
mutheta ~ dnorm (00 10E-6)tautheta lt- pow(sigmatheta -2)sigmatheta ~ dunif (0 1000)
if (isR()) for R some temporary filenamefilename lt- filepath(tempdir() schoolsmodelbug)
else for S-PLUS put the file in the working directoryfilename lt- schoolsmodelbug
write model filewritemodel(schoolsmodel filename) and lets take a lookfileshow(filename)
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
Index
lowastTopic IObugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic datasetsschools 21
lowastTopic dataattachall 3
lowastTopic filebugsdata 9bugsinits 10bugslog 11bugsscript 13bugssims 14bugsupdatesettings 14readbugs 20writemodel 22
lowastTopic hplotplotbugs 19
lowastTopic interfaceasbugsarray 2bugs 5openbugs 17
lowastTopic internalbugsdata 9bugsinits 10bugsplot 11bugsrun 12bugsscript 13bugssims 14bugsupdatesettings 14decodeparametername 15monitor 16writedatafile 21
lowastTopic manipasbugsarray 2
lowastTopic modelsbugs 5openbugs 17
lowastTopic packageR2WinBUGS-package 2
lowastTopic printprintbugs 19
asbugsarray 2attach 3 4attachall 3attachbugs (attachall) 3
BRugsFit 17bugs 2ndash4 5 10ndash16 18ndash20 22bugsdata 6 9 17bugsinits 10bugslog 11bugsplot 11bugsrun 12bugsscript 13bugssims 14 15bugsupdatesettings 12 13 14
cat 21convpar (monitor) 16
decodeparametername 15detach 4detachall (attachall) 3detachbugs (attachall) 3
environment 4
formatC 6 10 18formatdata (writedatafile) 21
mcmclist 20monitor 16
25
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-
26 INDEX
openbugs 3 6 17
plot 19plotbugs 2 9 12 19print 20printbugs 2 9 19
R2WinBUGS (R2WinBUGS-package) 2R2WinBUGS-package 2readbugs 6 7 20readcoda 20
schools 21
writedatafile 21writemodel 2 7 22writeLines 22
- R2WinBUGS-package
- asbugsarray
- attachall
- bugs
- bugsdata
- bugsinits
- bugslog
- bugsplot
- bugsrun
- bugsscript
- bugssims
- bugsupdatesettings
- decodeparametername
- monitor
- openbugs
- plotbugs
- printbugs
- readbugs
- schools
- writedatafile
- writemodel
- Index
-