Search code examples
rggplot2plotreportr-glue

How to combine outputs of different functions into a nicely report?


I have like:
. multiple plots, each created by a distinct function.

#Plot 1
sis_name <- babynames %>% 
  filter(name == "Kate", sex == "F") %>% 
  select("year", "name", "prop")

plot1 <- ggplot(data = sis_name) +
             geom_line(mapping = aes(x = year, y = prop)) +
             labs(title = "The Popularity of baby girls' name Kate", x = 
             "Year", y = "Proportion")

#Plot 2
plot2 <- ggplot(data = mydata) +
            geom_point(mapping=aes(x=X, y=Y), color="blue") +
            labs(title="Y vs X")

. some "text" outputs, created by glue::glue() and paste() functions.

conf_interval <- function(mydata) {
  model <- lm(Y~X, data = mydata)
  B_conf <- confint(model,                       #confidence interval for B
                    model$coefficients[2], 
                    level = 0.95
    glue::glue("Confidence interval for slop is {B_conf}")
}

What if I want to create a FUNCTION that calls out all the outputs (plot 1, plot 2, and the confidence interval) and combine them all into ONE nicely formatted report
(i.e. a sequence of plot and glue() commands from all the functions called sequentially)?
The requirement is to call out the report with a "function". Any suggestions on which functions that I should look at?


Solution

  • You can save the example below as a file called report.Rmd:

    ---
    title: "My Title"
    author: "Me"
    date: "21/08/2021"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    suppressPackageStartupMessages(
      library(tidyverse)
    )
    library(glue)
    ```
    
    # Title
    
    ```{r}
    ggplot(mpg, aes(displ, hwy)) +
      geom_point()
    ```
    
    Other variables include `r glue_collapse(colnames(mpg), sep = ", ", last = " and ")`.
    

    Subsequently, you can run the following:

    library(rmarkdown)
    render("report.Rmd", html_document())
    

    To produce the report.