Search code examples
rr-markdownstargazer

How to render output of stargazer in Rstudio's source pane?


First of all let me say that when I knit a full document that the output of stargazer is as expected. What I'd like to do is render it in my source pane under the block of code like I can with any other type of code, including plots. So far the best I've found is setting startype<-ifelse(is.null(opts_knit$get("rmarkdown.pandoc.to")), 'text', 'html') and then in my call to stargazer settings type=startype that way when I knit I get the fully formatted version but in my code chunk I still get something. I'd like to be able to get the fully formatted version so I can tweak the parameters according to how it'll finally look without having to knit the whole thing.

I'm on Windows with Rstudio version 1.4.1106

Is that possible?


Solution

  • Below I've created a simple wrapper around the stargazer function called starviewer that does the following:

    • check if the document is being knit to latex or html
    • if the document isn't being knit to latex, output to text or html
    • when run interactively in RStudio, output can appear inline as text and/or in the Viewer pane as html

    I'm not expert with the rstudioapi::viewer() options but this worked well on my system.

    For more on the rstudioapi, see: https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html

    Copy the following four code chunks into an Rmd and they should be able to run interactively or be knit to latex or html automatically depending on the user action.

    ```{r load_packages}
    # good to load stargazer for regular usage
    library(stargazer)
    ```
    
    ```{r starviewer_function}
    
    # create wrapper around stargazer
    starviewer <- function(...) {
      
      # make sure stargazer is available
      require(stargazer)
      
      # assume text output but check for latex or html
      star_format <- "text"
      if(knitr::is_latex_output()) {star_format <- "latex"}
      if(knitr::is_html_output())  {star_format <- "html"}
      
      # if latex, just run stargazer as usual
      if (star_format == "latex") {
        stargazer::stargazer(...)   
    
      } else {
    
      # if not latex, run stargazer in text / html (or both)  
        dir <- tempfile()
        dir.create(dir)
        htmlFile <- file.path(dir, "tempfile.html")
        stargazer::stargazer(..., type = star_format, out = htmlFile)
        rstudioapi::viewer(htmlFile)
      }
    }
    
    ```
    
    ```{r run_models}
    lm1 <- lm(mpg ~ wt,      data = mtcars )
    lm2 <- lm(mpg ~ wt + am, data = mtcars )
    ```
    
    ```{r create_table, results = 'asis'}
    starviewer(lm1, lm2)
    
    ```