简体   繁体   中英

How to convert MCMC diagnostics to Latex table?

I'm using the coda package to calculate the summary statistics of my MCMC. However, there seems to be no options to convert the printed summary into a Latex table. I've tried stargazer , and coercing summary.mcmc results to a data frame. Both attempts have failed.

Here's a reproducible example:

library(coda)
mock_mcmc <- mcmc(rnorm(1000))
summary(mock_mcmc)

summary.mcmc will print out

1. Empirical mean and standard deviation for each variable,
   plus standard error of the mean:

          Mean             SD       Naive SE Time-series SE 
       0.03180        0.98715        0.03122        0.03368 

2. Quantiles for each variable:

    2.5%      25%      50%      75%    97.5% 
-1.89794 -0.65289  0.02952  0.67396  1.97158 

How do I output that result table into a Latex file? I understand that it is possible to calculate the summary statistics by hand, but I'm curious whether there's a convenient feature of coda that I don't know about.

I don't know if there's a way to do it in coda. The method below defines a method of xtable for mcmc objects by converting the object to a dataframe and then rerunning xtable.

library(coda)
library(dplyr)
library(magrittr)
library(xtable)

xtable.summary.mcmc = function(x, ...)
  x %>%
  use_series(statistics) %>%
  c(x %>%
      use_series(quantiles) ) %>%
  as.list %>%
  dplyr::as_data_frame() %>%
  xtable(...)

1000 %>% 
  rnorm %>% 
  mcmc %>% 
  summary %>%
  xtable                    

The key is to extract the relevant quantities from the output. To find the appropriate quantities, use the names() function in R.

library(coda)
library(xtable)

mock_mcmc = mcmc(rnorm(1000))
s = summary(mock_mcmc)

stats_table = xtable(as.data.frame(t(s$statistics)))
quant_table = xtable(as.data.frame(t(s$quantiles)))

print(stats_table, file="stats_table.tex")
print(quant_table, file="quant_table.tex")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM