Regression Tables in R Markdown / rmarkdown (html/pdf)

后端 未结 2 1440
星月不相逢
星月不相逢 2021-01-19 12:00

For the purpose of publishing I often need both a PDF and a HTML version of my work including regression tables and I want to use R Markdown. For PDF the stargazer

相关标签:
2条回答
  • 2021-01-19 12:32

    Here is a proposition: make a function that checks the output format and then uses either stargazer or texreg depending on this. We use opts_knit$get("rmarkdown.pandoc.to") to check the output format.

    ---
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    library(knitr)
    opts_chunk$set(echo = TRUE)
    rmd_format <- opts_knit$get("rmarkdown.pandoc.to")
    ## returns "html" or "latex"
    
    ```
    
    ```{r}
    
    report_regression <- function(model, format, ...){
      if(format == "html"){
        require(texreg)
        htmlreg(model, custom.note="%stars. htmlreg", ...)
      } else if(format == "latex"){
        require(stargazer)
        stargazer(model, notes="stargazer html", ...)
      } else {
       print("This only works with latex and html output") 
      }
    }
    ```
    
    ```{r table, results = "asis"}
    library(car)
    lm1 <- lm(prestige ~ income + education, data=Duncan)
    
    report_regression(lm1, format = rmd_format)
    ```
    
    0 讨论(0)
  • 2021-01-19 12:32

    As pointed out in an answer to a related question, knitr 1.18 introduced the following functions

    knitr::is_html_output()
    knitr::is_latex_output()
    

    to check if the output is HTML or LaTeX. Adapting @scoa's excellent answer:

    ---
    output: html_document
    ---
    
    ```{r}
    
    report_regression <- function(model, ...){
      if(knitr::is_html_output()){
        require(texreg)
        htmlreg(model, custom.note="%stars. htmlreg", ...)
      } else if(knitr::is_latex_output()){
        require(stargazer)
        stargazer(model, notes="stargazer html", ...)
      } else {
       print("This only works with latex and html output") 
      }
    }
    ```
    
    ```{r table, results = "asis"}
    library(car)
    lm1 <- lm(prestige ~ income + education, data=Duncan)
    
    report_regression(lm1)
    ```
    
    0 讨论(0)
提交回复
热议问题