Search code examples
rlabelstargazerexpss

label variable for stargazer extraction


I am using stargazer to extract some regression tables in latex. I would to know if it exists a way to label variables once for all without having to re-define it through "covariate.labels = ..." every time. I tried the library expss (and Hmisc), such as:

library(expss)
library(stargazer)

df <- data.frame(replicate(2,sample(0:1,100,rep=TRUE)))

df = apply_labels(df,
                  X1 =  "label x1",
                  X2 = " label x2")

ols <- lm(formula = X1 ~ X2,
          data= df)

stargazer(ols, 
          # covariate.labels = NULL, 
          title = "Regression Results",
          label = "tab:test",
          out="test.tex")

without success... any suggestion?


Solution

  • Solution with expss use_labels:

    library(expss)
    library(stargazer)
    
    df <- data.frame(replicate(2,sample(0:1,100,rep=TRUE)))
    
    df = apply_labels(df,
                      X1 =  "label x1",
                      X2 = " label x2")
    
    ols <- use_labels(df, lm(formula = X1 ~ X2))
    
    res <- stargazer(ols, 
              # covariate.labels = NULL, 
              title = "Regression Results",
              label = "tab:test",
              out="test.tex")
    
    # quick and dirty workaround for removing backticks  
    remove_backticks = function(text){
        text = gsub("([^A-z]+)`", "\\1", text, perl = TRUE)
        text = gsub("`([^A-z]+)", "\\1", text, perl = TRUE)
        text = gsub("(^`)|(`$)", "", text, perl = TRUE)
        text
    }
    
    
    res = remove_backticks(res)
    
    writeLines(res, "test.tex")