How do I resize tables created by Stargazer in R Markdown?
I have included resize.height=0.5,resize.width=0.5
in a piece of code but cannot resize the table created by stargazer. Can anyone tell me why?
The parameters of my code-behind look like this:
echo=FALSE,warning=FALSE,results='asis',resize.height=0.5,resize.width=0.5}
Stargazer codes are as follows:
stargazer(did.student,student.control.kmt,student.control.neu,student.control.dpp,header = FALSE,
title="DD Model",
covariate.labels = c("Treatment","group","Treatment*group"),
dep.var.labels = "attitude",
column.labels = c("","party1","Independent","party2"),
label = "DiD-students")
Would be grateful for any help!
- Forgot to mention - I'm using a chart with a table.
source to share
I'll solve the problem myself:
To adjust the table size with stargazer, you can change the font size font.size=
, make a single Stargazer row, single.row = TRUE
and change the spacing between columns column.sep.width = "1pt"
in stargazer()
.
While the link here suggests using print(stargazer(),scalebox='0.7')
, it doesn't work for me, perhaps because I'm using Markdown with Beamer, but I'm not sure, I still wish I had more input on this.
I was hoping for a simpler answer, but it works!
source to share
This GitHub comment inspired me to implement \resizebox{}
in stargazer()
. You can use resizebox.stargazer()
to specify the size of the table output from stargazer()
s tab.width
and / or tab.height
. To activate the function, you first need to run the following code:
resizebox.stargazer = function(..., tab.width = "!", tab.height = "!" ){ #Activate str_which() function: require(stringr) #Extract the code returned from stargazer() res = capture.output( stargazer::stargazer(...) ) #Render the arguments: tab.width = tab.width tab.height = tab.height #Attach "}" between \end{tabular} and \end{table} res = prepend(res, "}", before = length(res)) #Input \resizebox before \begin{tabular} res = c(res[1:str_which(res, "^\\\\begin\\{tabular\\}.*")-1], paste0("\\resizebox{",tab.width,"}{",tab.height,"}{%"), res[str_which(res, "^\\\\begin\\{tabular\\}.*"):length(res)] ) #Produce the whole strings cat(res, sep = "\n") }
You can specify the size of the table, for example resizebox.stargazer(..., tab.width = "0.7\\textwidth")
. Note that you must write TeX commands from \\
instead of \
.
source to share
Here is an alternative to Carlos' solution that writes the output to a LaTeX file:
mkTexTable <- function(..., file){
tbl <- capture.output({
stargazer(...)
})
tbl <- gsub("\\begin{tabular}", "\\resizebox{\\textwidth}{!}{\\begin{tabular}", tbl, fixed = T)
tbl <- gsub("\\end{tabular}", "\\end{tabular}}", tbl, fixed = T)
fileConn <- file(file)
writeLines(tbl, fileConn)
close(fileConn)
}
mkTexTable(lm1, lm2, "texOutput.tex")
This post also provided some help: fooobar.com/questions/4851780 / ...
source to share