As others note, the issue arises with special characters in the covariate.labels argument. The recommended solutions, however, miss a few things:
- With latex output, you can use
\\
to 'escape' special characters so that they appear properly. You can also use the command xtable::sanitize("Sexual_Disgust_std", type = "latex")
to convert a string to something more latex friendly. In the original example, that would be:
`covariate.labels = c("Gender", "Sexual\\_Disgust\\_std")`
- With latex output, some special characters are mathematical and they need to be enclosed in a math mode syntax. For example, if two covariates were % Black and (% Black)-squared, one might write:
`covariate.labels = c("\\% Black", "(\\% Black)$^2$")`
- The original question appears to write to a
.htm
file but does not specify in stargazer type = 'html'
so the default will be type = 'latex'
. If switching between latex and html output, some of the latex encodings can break the html generation. I'm not aware of an elegant solution to this issue but if you're using knitr
with R Markdown or Sweave, you could use the functions: knitr:: is_latex_output()
or knitr::is_html_output()
to generate latex or html appropriate code as in:
library(knitr)
library(dplyr)
library(stargazer)
star_format <- dplyr::case_when(
knitr::is_latex_output() ~ "latex",
knitr::is_html_output() ~ "html",
TRUE ~ "text" # for interactive coding in console
)
# One way would be to build latex / html specific labels
covar_labels <- dplyr::case_when(
knitr::is_latex_output() ~ c("Gender", "Sexual\\_Disgust\\_std"),
knitr::is_html_output() ~ c("Gender", "Sexual Disgust std"),
TRUE ~ c("Gender", "Sexual Disgust std")
)
# for simplicity, stargazer call doesn't include custom dep.var.labels or out arguments
stargazer(lm_1, lm_2, lm_3, lm_4,
type = star_format,
covariate.labels = covar_labels)
# A second way would be to create separate stargazer calls:
if(knitr::is_html_output()) {
stargazer(lm_1, lm_2, lm_3, lm_4,
type = star_format,
dep.var.labels = c("PolOri Social std", "Sexual Disgust std"),
covariate.labels = c("Gender", "Sexual Disgust std"),
style = "demography",
out = "hierarchical.html",
header = FALSE)
}
if(knitr::is_latex_output()) {
stargazer(lm_1, lm_2, lm_3, lm_4,
type = star_format,
dep.var.labels = c("PolOri\\_Social\\_std", "Sexual\\_Disgust\\_std"),
covariate.labels = c("Gender", "Sexual\\_Disgust\\_std"),
style = "demography",
out = "hierarchical.tex",
header = FALSE)
}
- Using the same
knitr::is_latex_output()
and knitr::is_html_output()
functions, one could also pre-process any labels with regex to be specifically formatted for html or latex output. For example, below is a small function that would search and replace various special characters text strings.
library(stringr)
remove_special_chars <- function(covar_labels){
covar_labels %>%
str_replace_all("\\\\", "") %>%
str_replace_all("\\^", "") %>%
str_replace_all("_", " ") %>%
str_replace_all("\\$", "") %>%
str_replace_all("`", "'")
}