Home > Software design >  How to color negative estimates in red in stargazer model table?
How to color negative estimates in red in stargazer model table?

Time:12-28

Is it possible to color the font of negative model estimates red in a stargazer table in R?

The idea is to more easily highlight negative and positive estimates when showcasing a regression model in a table.

CodePudding user response:

I don't think it's possible with stargazer out of the box, but you could write your own functions to accomplish this.

For example, using the LaTeX package xcolor, we can create red text with the command \textcolor{red}{text}. Since stargazer prints negative numbers as $-$<number>, we can use the regex \\$-\\$[0-9] to find all negative numbers ( some logic for commas etc.), and wrap them in \textcolor{red}{text}.

Here is a working example:

make_red <- function(str) {
  
  paste0(
    "\\textcolor{red}{",
    str,
    "}"
  )
  
}

library(dplyr)

mtcars %>% 
  # Add some negative numbers
  mutate(
    negative_values = -cyl
  ) %>% 
  stargazer::stargazer() %>% 
  stringr::str_replace_all(
    pattern = "\\$-\\$[0-9][.]?[0-9]*",
    replacement = make_red
  ) %>% 
  writeLines()

Note that this will print two LaTeX outputs, because stargaze() always prints it's output when called. You only need the bottom one.

Remember to add \usepackage{xcolor} at the start of your LaTeX document.

The result after compiled LaTeX:

Final result

  • Related