I want to print a latex table generated with stargazer() in monospaced font, and I want to do it in a reproducible way with knitr (i.e., no manual latex coding). I tried to define an environment called mymono and then wrap the knitr chunk in this environment via \begin{} and \end{}. It does not work; the table prints in the default font style.
\documentclass{article}
\newenvironment{mymono}{\ttfamily}{\par}
\begin{document}
<<lm, echo=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
@
% reproducible
\begin{mymono}
<<table_texstyle, echo=FALSE, results='asis', message=FALSE>>=
stargazer(lm1, label="test")
@
\end{mymono}
\end{document}
I don't think there is a font setting in stargazer() except for font.size.
# > sessionInfo()
# R version 3.0.2 (2013-09-25)
# Platform: x86_64-apple-darwin10.8.0 (64-bit)
# other attached packages:
# [1] stargazer_5.1
Even better than wrapping the entire table{} in the new font style would be to wrap just tabular{} so that the caption remains the default style. I don't know if there is a way to insert latex code into the stargazer() output programmatically.
Too long for a comment, so here's a start of an answer. Using the model from the question:
\documentclass{article}
\begin{document}
<<lm, echo=FALSE, message=FALSE, include=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
tabular_tt <- function(orig.table) {
library(stringr)
tabular.start <- which(str_detect(orig.table, "begin\\{tabular\\}"))
tabular.end <- which(str_detect(orig.table, "end\\{tabular\\}"))
new.table <- c(orig.table[1:(tabular.start - 1)],
"\\texttt{",
orig.table[tabular.start:tabular.end],
"}",
orig.table[(tabular.end + 1):length(orig.table)])
return(new.table)
}
@
<<print, results='asis', echo=FALSE>>=
cat(tabular_tt(capture.output(stargazer(lm1, label="test"))), sep="\n")
@
\end{document}
You can easily adjust it as necessary. If you're having trouble, I would make sure your target LaTeX syntax is correct by playing with a small toy table in LaTeX only, maybe playing with the tex file generated when you knit.
You may need to make the function cat(new.table, sep = "\n") to get it to get the output correctly into the knitr document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With