在 Rmarkdown 中使用 apsrtable 的多个 lm() 模型表 [英] Table of multiple lm() models using apsrtable in Rmarkdown

查看:16
本文介绍了在 Rmarkdown 中使用 apsrtable 的多个 lm() 模型表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Goal

Present the results of multiple models, created using the lm() function, together in a nicely-formatted table. This table will be generated in a .Rmd file and output to a PDF document.

Proposed Solution

In Reproducible Research with R and RStudio, there is an example using the apsrtable() function to display multiple models side-by-side. This book provides the following code (p. 173-174):

Code

egin{table}
    caption{Example Nested Estimates Table with emph{aprstable}}
    label{BasicApsrTableExample}
        egin{center}
<<results= asis , echo=FALSE>>=
# Load apsrtable package
library(apsrtable)
# Create nested regression model table
apsrtable(M1, M2, M3, M4, M5, Sweave = TRUE,
      stars = "default")
@
       end{center}
end{table}

where the models M1 ... M5 are created in chunks using M2 <- lm(Examination ~ Education + Agriculture, data = swiss).

Output

Below is a screen grab of the results, as reported in the book. This is exactly the table I want to create in my .Rmd file and output to a PDF document.

Issues

Attempt 1 When I try to use this code inside a code chunk—as shown below—and the output to a PDF, I get a an error message: Error: $ operator is invalid for atomic vectors

```{r}
t.model2 = xtable(model2,label = NULL)
t.model3 = xtable(model3,label = NULL)

library(apsrtable)

apsrtable(t.model2, t.model3, Sweave = TRUE, stars = "default")
```

Attempt 2 When I use the above code outside a code chunk, the .Rmd file outputs to PDF, but displays the following:

Questions

My Questions

  • Why are these attempts failing?
  • What is the correct way to use the apsrtable function inside a .Rmd?
  • Will this method work to ouput this .Rmd file to PDF?

Related Stack Overflow Questions

解决方案

You need to take care of the following two things:

  • Chunk option results='asis'
  • usepackage{dcolumn} must be in the preamble as stated in the help file.

Another option would be the stargazer package, which allows to knit not only to PDF but to HTML as well (see screenshot).

---
title: "stargazer"
author: "hplieninger"
date: "3 August 2018"
output: pdf_document
header-includes:
    - usepackage{dcolumn}
---

```{r}
m1 <- lm(Fertility ~ Education , data = swiss)
m2 <- lm(Fertility ~ Education + Agriculture, data = swiss)
m3 <- lm(Fertility ~ . , data = swiss)
```

```{r, results='asis'}
apsrtable::apsrtable(m1, m2, m3, Sweave = TRUE)
```

```{r, results='asis'}
# If output: pdf_document
stargazer::stargazer(m1, m2, m3)
# If output: html_document
# stargazer::stargazer(m1, m2, m3, type = "html")
```

这篇关于在 Rmarkdown 中使用 apsrtable 的多个 lm() 模型表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆