New font style for stargazer latex table when using knitr

I want to print a latex table generated using stargazer()

in a monospaced font and I want to do it in a reproducible way with knitr

(i.e. hand-coding latex). I tried to define an environment named mymono

and then wrap a knitr block in that environment through \begin{}

and \end{}

. This 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 stargazer()

there is a font setting in there other than 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 everything table{}

in a new font style would be to wrap just tabular{}

so the heading remains the default style. I don't know if there is a way to insert latex code into the output stargazer()

programmatically.

+3


source to share


1 answer


Too long for a comment, so here is the beginning of the 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 needed. If you're having trouble, I would make sure your target LaTeX syntax is correct by playing with the little toy table in LaTeX only, perhaps playing with the tex file created by knitting.

You may need to make a function cat(new.table, sep = "\n")

to get it to correctly output the output to the knitr document.

+2


source







All Articles