title: R2WinBUGS - logistic regression with simulated data
body: <p>I am just wondering whether anyone has some R code that uses the package R2WinBUGS to run logistic regression - ideally with simulated data to generate the 'truth' and two continous co-variates.</p>
  
  <p>Thanks.</p>
  
  <p>Christian</p>
  
  <p>PS:</p>
  
  <p>Potential code to generate artificial data (one dimensional case) and run winbugs via r2winbugs (it does not work yet).</p>
  
  <pre><code>library(MASS)
  library(R2WinBUGS)
  
  setwd("d:/BayesianLogisticRegression")
  
  n.site &lt;- 150
  
  X1&lt;- sort(runif(n = n.site, min = -1, max =1))
  
  xb &lt;- 0.0 + 3.0*X1 
  
  occ.prob &lt;- 1/(1+exp(-xb))
  
  plot(X1, occ.prob,xlab="X1",ylab="occ.prob")
  
  true.presence &lt;- rbinom(n = n.site, size = 1, prob = occ.prob)
  
  plot(X1, true.presence,xlab="X1",ylab="true.presence")
  
  # combine data as data frame and save
  data &lt;- data.frame(X1, true.presence)
  write.matrix(data, file = "data.txt", sep = "\t")
  
  sink("model.txt")
  cat("
  model {
  
  # Priors
   alpha ~ dnorm(0,0.01)
   beta ~ dnorm(0,0.01)
  
  # Likelihood
   for (i in 1:n) {
      C[i] ~ dbin(p[i], N)        # Note p before N
      logit(p[i]) &lt;- alpha + beta *X1[i]
   }
  }
  ",fill=TRUE)
  sink()
  
  # Bundle data
  win.data &lt;- list(mass = X1, n = length(X1))
  
  # Inits function
  inits &lt;- function(){ list(alpha=rlnorm(1), beta=rlnorm(1))}
  
  # Parameters to estimate
  params &lt;- c("alpha", "beta")
  
  # MCMC settings
  nc &lt;- 3 #Number of Chains
  ni &lt;- 1200 #Number of draws from posterior
  nb &lt;- 200 #Number of draws to discard as burn-in
  nt &lt;- 2 Thinning rate
  
  # Start Gibbs sampling
  out &lt;- bugs(data=win.data, inits=inits, parameters.to.save=params, 
  model.file="model.txt", n.thin=nt, n.chains=nc, n.burnin=nb, 
  n.iter=ni, debug = TRUE)
  </code></pre>