The R
package MCMCpack
offers Bayesian logistic regression through MCMClogit
. This function prints the acceptance rate of the MCMC (Metropolis-Hastings) algorithm if verbose=TRUE
but it does not seem to return it in the mcmc
object. Is there a way to access this information in the object?
To test use:
library(MCMCpack)
set.seed(12345)
n = 1000
x = rnorm(n)
y = rbinom(n,1,1/(1+exp(-(1 + x))))
m = MCMClogit(y ~ x, burnin = 5000, mcmc = 1000,
tune = 1.3, B0 = 0, verbose = TRUE)
Which prints an acceptance rate of 0.45533
but I do not find this information in names(m)
returning NULL
or names(attributes(m))
which returns
[1] "dim" "mcpar" "class" "dimnames" "title" "y" "call"
The help file suggests that the coda
package allows sumarizing information from mcmc
objects (see coda) but searching for 'acceptance' in the pdf does not yield any results.
If you don't like the behavior of capture.output
, you can use sink
instead, which still returns the results but redirects the console output into a file.
sink(file="test.txt")
m <- MCMClogit(y ~ x, burnin = 5000, mcmc = 1000,
tune = 1.3, B0 = 0, verbose = TRUE)
sink()
out <- readLines("test.txt")
grep( "acceptance rate for beta was", out, value=T)
# [1] "The Metropolis acceptance rate for beta was 0.45533"
class(m)
# [1] "mcmc"
No need for assign
or <<-
.
If you want to have it as a numeric value, you can extract it as follows.
ar <- grep( "acceptance rate for beta was", out, value=T)
ar <- as.numeric( gsub("^.* was (.*)", "\\1", ar) )
ar
# [1] 0.45533