Home > Mobile >  Flextable: make the signif stars bold and remove the space between stars and the coefficient
Flextable: make the signif stars bold and remove the space between stars and the coefficient

Time:12-04

I'm testing flextable, a package for R by David Gohel, for the publication workflow and I was wondering about how to format substrings in the cells of the regression tables. In particular, I aim to replicate Stata's outreg2 with significance stars in bold and right next to the coefficient.

Here is the reprex:

library(huxtable)
library(flextable)
lm(formula=mpg~cyl hp, mtcars) %>% huxreg() %>% as_flextable()

enter image description here

Now I am trying to make the significance stars in bold and right next to the coefficient without the space in between.

If anyone could chime in, it would be great! I'm looking at ftExtra but I see no way how to approach this.

Thank you!

CodePudding user response:

With flextable, you can do it quite easily by adding a signif. column after the p-values column and use 0 padding.

The following code demo how to do it from scratch:

x <- lm(formula=mpg~cyl hp, mtcars)

library(flextable)
library(broom)
library(magrittr)

pvalue_format <- function(x){
  z <- cut(x, breaks = c(-Inf, 0.001, 0.01, 0.05, 0.1, Inf), labels = c("***", "**", "*", ".", ""))
  as.character(z)
}

tidy(x) %>% 
  flextable(
    col_keys = c("term", "estimate", "std.error", "statistic", "p.value", "signif")) %>% 
    colformat_double(digits = 4) %>% 
  mk_par(j = "signif", value = as_paragraph(pvalue_format(p.value)) ) %>% 
  set_header_labels(term = "", estimate = "Estimate",
                        std.error = "Standard Error", statistic = "t value",
                        p.value = "Pr(>|t|)", signif = "" ) %>% 
  align(j = "signif", align = "left") %>% 
  padding(padding.right = 0, j = "p.value", part  = "all") %>% 
  padding(padding.left = 0, j = "signif", part  = "all") %>% 
  autofit()

enter image description here

You can also use the flextable::as_flextable method and adapt the result to your needs:

as_flextable(x) %>% 
  delete_part(part = "footer") %>% 
  padding(padding.right = 0, j = "p.value", part  = "all") %>% 
  padding(padding.left = 0, j = "signif", part  = "all") %>% 
  color(i = ~ p.value > .05, j = "p.value", color = "gray") %>% 
  theme_vanilla()

enter image description here

  • Related