1

I need to produce a LaTeX table completely in R, so that if the values in the table change over the course of analysis, the formatting of the table remains the same.

I am passing a matrix of values (a balance table for an RCT if there are any economists out there) into stargazer. It mostly gets the table right. However, the first column is center-aligned and I need it to be left-aligned.

No online solutions have worked to date.

I have read this solution (how to align stargazer table to the left when type="latex"?) and am able to create a string that replaces "ccccc" with "lcccc" which, when pasted into a .tex file, does succeed in left-aligning my first column. BUT it does not output the result of cat(out) into a .tex file. I could copy-paste this into a new file, but then would have to repeat this for each table I am creating for the project, every time I run my code and leaves room for errors. I need my code to be fully replicable.

I had hoped that downloading the package starpolishr (https://github.com/ChandlerLutz/starpolishr) could allow me to edit code within R more easily, but I have not figured out how to use it in this capacity.

This is my matrix

balance.table <- rbind(balance.table, num.kids, num.awc, f.stat, f.stat.prob)

Exported using stargazer to balance_table.tex

stargazer(balance.table, type="latex",
          title ="Balance table",
          digits = 2, 
          float = FALSE,
          header = TRUE,
          rownames = FALSE,
          out = paste0(exhibits, "balance_table.tex"))

From this, the first line of LaTeX output is:

\begin{tabular}{@{\extracolsep{5pt}} ccccc} 

Here is my attempt to edit it based on the example linked above:

starout <- capture.output(
  stargazer(balance.table, type="latex",
            title ="Balance table",
            digits = 2, 
            float = FALSE,
            header = FALSE,
            rownames = FALSE,
            out = paste0(exhibits, "balance_table2.tex")))

starout <- sub(" ccccc", " lcccc", starout)
cat(starout) 

This results in the updated first line of LaTeX code:

\begin{tabular}{@{\extracolsep{5pt}} lcccc} 

However, I have no way to now export this to LaTeX. The output IS a file called "balance_table2.tex" but it is the same as "balance_table.tex" and has "ccccc" instead of "lcccc".

Is there some way to export the result of cat() to a .tex file? Or is there a way to get the alignment using starpolishr or some other fully replicable method?

Thanks!

hannahb
  • 11
  • 2

1 Answers1

0

You can use writeLines(starout, "balance_table.tex") after the substitution. See this SO post for some alternative solutions.

sboysel
  • 631
  • 7
  • 17