This doesn't solve the problem, but perhaps points to the culprit. First, it doesn't look like there is an alignment option when the output is "text"
. I tried to force the alignment changing the numbers into character strings as follows:
df<-data.frame(x=c(1.33,-1.23,23.4343,-3000))
format_decimal <- function(x, digits=2){
s <- stringr::str_split(as.character(x), "\\.", simplify=TRUE)
mchar <- apply(nchar(s), 2, max)
sprintf(paste0("%", mchar[1]+digits, ".", digits, "f"), x)
}
library(dplyr)
df <- df %>% mutate(across(where(is.numeric), format_decimal))
When you print the data frame (outside of stargazer), you see that the values are left-aligned (which makes them decimal aligned when you print a fixed number of decimal places).
df
# x
# 1 1.33
# 2 -1.23
# 3 23.43
# 4 -3000.00
However, when you use the same data in stargazer, the data are now centered.
stargazer(df, type = "text",
title = "Align me plz",
rownames = FALSE,
colnames = FALSE,
summary = FALSE
)
# Align me plz
# ========
# 1.33
# -1.23
# 23.43
# -3000.00
# --------
So, it looks like the internals of the function trim and pad the values so they are centered. To solve the problem, you would likely have to fiddle with the internals of the package. There is a function that gets defined in there called .trim
which shaves off leading and trailing spaces. I tried to re-define that as .trim = function(x)x
, but that didn't solve the problem either. So it might be that changing that in coordination with changing something else or changing something else entirely is required.