一直以来R生成的结果简单粗暴,不符合论文投稿需要,相对而言stata输出的结果符合期刊杂志的格式要求。这里我们推荐stargazer包,它可以帮助我们优雅地将回归结果放在一张表格中,效果堪比stata中的outreg2。

加载相关包

1
2
3
library(ggplot2)
library(zoo)
library(stargazer)

加载数据

1
2
3
4
mydata = read.csv("~/mydata/mydataviz.csv", header = TRUE, stringsAsFactors = FALSE)
mydata$date = as.Date(mydata$date ,"%m/%d/%Y")
mydata = mydata[order(mydata$date ),]
mydata$month = as.yearmon(mydata$date )

数据可视化

1
2
3
plot(mydata$month, mydata$unemp, type = "l", 
     ylim = c(0, 12), xlab = "Month",
     ylab = "Unemployment(%)", main = "Unemployment")

回归分析

1
2
3
4
5
6
7
reg1 = lm(unemp ~ approve, data = subset(mydata, party == "Democrat"))
reg2 = lm(unemp ~ approve, data = subset(mydata, party == "Republican")) 
stargazer(reg1, reg2, type = "html", out="models.htm",
          model.numbers = FALSE,
          dep.var.labels=c("Presidential Approval"), 
          column.labels =c("Democrats", "Republicans"), 
          covariate.labels =c("Unemployment rate"))

生成的表格将保存在models.htm文件中,你可以用word来打开这个文件,复制后放在论文中即可。