I'm trying to compile a LaTeX report using RStudio and knitr
. I'm having a hard time getting the packages booktabs
and dcolumn
to work with my texreg
-generated table.
As an example, I am trying to recreate Table 2 in this example:.
My attempt as a .Rnw -file is below:
\documentclass{article}
\usepackage{booktabs}
\usepackage{dcolumn}
<<setup, include=FALSE >>=
library(texreg)
@
\begin{document}
<<analysis, include=FALSE>>=
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2,10,20, labels=c("Ctl","Trt"))
weight <- c(ctl, trt)
m1 <- lm(weight ~ group)
m2 <- lm(weight ~ group - 1) # omitting intercept
@
<<table, results='asis'>>=
texreg(m2)
@
\end{document}
However, the generated LaTex table (below) includes neither the booktabs
horizontal lines nor the dcolumn
alignment. How to incorporate them? Many thanks for help!
\begin{table}
\begin{center}
\begin{tabular}{l c }
\hline
& Model 1 \\
\hline
groupCtl & $5.03^{***}$ \\
& $(0.22)$ \\
groupTrt & $4.66^{***}$ \\
& $(0.22)$ \\
\hline
R$^2$ & 0.98 \\
Adj. R$^2$ & 0.98 \\
Num. obs. & 20 \\
\hline
\multicolumn{2}{l}{\scriptsize{$^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$}}
\end{tabular}
\caption{Statistical models}
\label{table:coefficients}
\end{center}
\end{table}
Just to clarify: the crucial part in Robert's solution is the argument
use.packages=FALSE
not the seperation of code into two chunks.The reason is the following: The way you call
texreg()
now makes it include the following in the tex output it produces:Saving the output in an object and then using
cat()
does not solve this.You cannot use
\usepackage()' outside the preamble. Knitr still compiles a PDF but apparently this use of
\usepackage{}' in the document body screws up the use of booktabs and dcolumn even if you've loaded them in the preamble.Add the argument
use.packages=FALSE
intexreg()
- if set to FALSE, the use package statements are omitted from the output. Write the use package statements into the preamble of your document yourself and you'll have the regression table with booktabs and aligned numbers.