建立回归结果表

时间:2019-02-18 15:56:41

标签: r knitr lm kable

我正在尝试建立回归结果表,但被卡住了。我收到错误消息:

  

who iteration value1 value2 1 1 1 1 2 1 1 2 3 1 2 1 4 1 0 0 1 2 1 1 2 2 1 2 3 2 2 1 3 3 2 1 5 3 0 0 中的错误:下标超出范围。

我已经运行了所有这些模型并将其标记为。我希望桌子看起来像什么:

summary(mod)$coefficients[vars, "Estimate"]

我的功能是从估计的模型中提取关键回归结果

 |          |  model1L |  model2L |  model3L |  model1P |  model2P |  model3P |
 |----------|----------|----------|----------|----------|----------|----------|
 |price     |   coef1L |   coef2L |   coef3L |   coef1P |   coef2P |   coef3P |
 |          |     sd1L |     sd2L |     sd3L |     sd1P |     sd2P |     sd3P |
 |promoflag |   coef1L |   coef2L |   coef3L |   coef1P |   coef2P |   coef3P |
 |          |     sd1L |     sd2L |     sd3L |     sd1P |     sd2P |     sd3P |

建立表格

model_list = c("model1L","model2L","model3L", "model1P", "model2P", "model3P")
vars = c("price","promoflag")

输出样本结果表

results_table1 = function(model_list, vars) {
  # build leftmost column of results table  
  outrec = c()
  for (j in 1:length(vars)) {
    outrec = c(outrec,sprintf("%s",vars[j]))
    outrec = c(outrec,"")
  }
  outrec = c(outrec,"R^2")
  outrec = c(outrec,"Observations")
  outdf = as.data.frame(outrec) 
  # process each model
  for (i in 1:length(model_list)) {
    # extract estimates for this model
    mod = eval(parse(text=model_list[i]))
    estimates = summary(mod)$coefficients[vars,"Estimate"]
    ses = summary(mod)$coefficients[vars,"Std. Error"]
    pvals = summary(mod)$coefficients[vars,"Pr(>|t|)"]
    # process each parameter of interest
    outrec = c()
    for (j in 1:length(vars)) {
      # set significance stars
      star = ""
      if (pvals[j] <= .05) {star = "*"}
      if (pvals[j] <= .01) {star = "**"}
      if (pvals[j] <= .001) {star = "***"}
      # output estimate and std err
      outrec = c(outrec,sprintf("%.4f%s",estimates[j],star))
      outrec = c(outrec,sprintf("(%.4f)",ses[j]))
    }
    # add R^2, # of observations to output
    outrec = c(outrec,sprintf("%.4f",summary(mod)$r.squared[1]))
    outrec = c(outrec,sprintf("%d",nobs(mod)))
    outdf = cbind(outdf,outrec)
  }
  # set column names to model names
  names(outdf) = c("",model_list)
  outdf
}

0 个答案:

没有答案