Michael Ohlrogge
Michael Ohlrogge

Reputation: 10980

R Stargazer - Manually Specify R^2 And Write to .tex

I am using Stargazer to report the results from some models where I use robust standard errors. The process of calculating these and then feeding the models to Stargazer strips out data such as R^2 and so I need to add it in manually. Doing so, however, is causing me problems. Below is the basic stargazer() call that I'm trying to run. Following it and some discussion is the code needed to generate the data going into the stargazer() call:

stargazer(fit1_robust, fit2_robust,
    keep.stat = c("n", "adj.rsq"), # doesn't actually result in keeping the stats, but including it just to demonstrate such.
    add.lines = list(c("Adjusted $R^2$", fit1_r2, fit2_r2)),
    out = "~/Test.tex"
    )

When I call this, I get the following error:

Error in if (nchar(text.matrix[r, c]) > max.length[real.c]) { : 
missing value where TRUE/FALSE needed

There are some interesting aspects to this:

Addressing either of these bullets "solves" the error, but at the expense of my code not really doing what I want it to. How can I manually add the adjusted R^2 in the way I've done here (and more generally, add notes involving ^)?

(Note: I also tried escaping the ^ character, replacing it with /^. That gave an error. If I use a double escape: //^ that prevents the error, but then a single escape shows up in the generated .tex file and that's not what I want.)

Here is the rest of the code to get to the point of having all objects needed for the above stargazer() call:

library(stargazer)
library(lmtest)
library(sandwich)

#################
# Simulate Data #
#################

N = 100

A = rnorm(N)
B = rnorm(N)
Y = 2*A + B + rnorm(N)
Data = data.frame(Y, A, B)

#####################################
# Fit Models and Find Robust Errors #
#####################################

fit1 = lm(Y~A)
fit2 = lm(Y~A+B)

fit1_robust = coeftest(fit1, vcov = sandwich)
fit2_robust = coeftest(fit2, vcov = sandwich)

fit1_r2 = round(summary(fit1)$adj.r.squared, 4)
fit2_r2 = round(summary(fit2)$adj.r.squared, 4)

Upvotes: 5

Views: 3311

Answers (1)

dww
dww

Reputation: 31452

One workaround is to save the output of stargazer in a variable, then write it to file afterwards:

star = stargazer(fit1_robust, fit2_robust,
  add.lines = list(c("Adjusted $R^2$", fit1_r2, fit2_r2))
)
cat(star, sep = '\n', file = 'Test.tex')

enter image description here

Upvotes: 4

Related Questions