Search code examples
ralignmentlatexr-markdownstargazer

how to align stargazer table to the left when type="latex"?


I use stargazer package in my automated rmarkdown pdf documents to make nice looking tables. Stargazer places its tables in the center of the page, by default. How can I let stargazer generate latex code that aligns the table to the left?

here is an example of what I mean:

library(stargazer)

data_object <- structure(list(test = structure(c(1L, 1L, 2L, 2L), .Label = c("test1",  "test2"), class = "factor"), test2 = structure(1:4, .Label = c("1",        "2", "3", "4"), class = "factor")), .Names = c("test", "test2"), row.names = c(NA, -4L), class = "data.frame")

stargazer(data_object,title="table test",summary=FALSE,rownames=FALSE,type="latex",header=FALSE)

the code it produces is:

\begin{table}[!htbp] \centering 
  \caption{table test} 
  \label{} 
\begin{tabular}{@{\extracolsep{5pt}} cc} 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
test & test2 \\ 
\hline \\[-1.8ex] 
test1 & 1 \\ 
test1 & 2 \\ 
test2 & 3 \\ 
test2 & 4 \\ 
\hline \\[-1.8ex] 
\end{tabular} 
\end{table}

Note the \centering. How can I change that without having to alter the latex code itself?


Solution

  • It would appear \centering is hard coded into the function. What you could do is delete \centering using sub (e.g. sub(" \\\\centering", "", out)).

    Here's the chunk I used. I used capture.output to prevent stargazer to output what I consider intermediate result.

    <<results = "asis">>=
    library(stargazer)
    
    data_object <- structure(list(test = structure(c(1L, 1L, 2L, 2L), .Label = c("test1",  "test2"), class = "factor"), test2 = structure(1:4, .Label = c("1",        "2", "3", "4"), class = "factor")), .Names = c("test", "test2"), row.names = c(NA, -4L), class = "data.frame")
    
    out <- capture.output(stargazer(data_object,title="table test",summary=FALSE,rownames=FALSE,type="latex",header=FALSE))
    out <- sub(" \\\\centering", "", out)
    cat(out)
    @
    

    enter image description here