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

本秂侑毒 提交于 2019-12-19 08:58:39

问题


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:

  • The error does not occur if I omit the ^ and instead just use "Adjusted $R2$"

  • The error does not occur if I don't use the out argument to specify a .tex file to export to.

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)

回答1:


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')



来源:https://stackoverflow.com/questions/44318860/r-stargazer-manually-specify-r2-and-write-to-tex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!