Last active
February 26, 2021 10:50
-
-
Save mathzero/98a10fc4d7d8b35dd7d765dfa291425e to your computer and use it in GitHub Desktop.
RMarkdown report automator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' This short function takes some input from whatever R script you are working in and creates an | |
#' rmarkdown document and corresponding knitted HTML file on the fly | |
#' Basis for code is: https://stackoverflow.com/questions/60110904/how-to-generate-html-report-directly-from-r-script | |
my_markdown_rederer <- function(text, myList=myList) { | |
# The file name for the rmd doc | |
rmd_file_name <- "temp.Rmd" | |
# Your YAML metadata for the doc | |
yaml_header <- "--- | |
title: 'My new report' | |
author: 'My name' | |
output: | |
html_document: | |
toc: true | |
fig_caption: true | |
theme: flatly | |
---" | |
# This is where all your content for the doc goes | |
# You will need to put everything inside quotes, including when you want to call | |
# the input to your function | |
content <- paste0(yaml_header, | |
"\n", | |
"\n", | |
"# Here is a test header \n | |
And here is some more dummy text \n", | |
"`r {text}` \n", # if you want to pass an r object to output in the text secion, you wrap it in r ticks, like this | |
"```{r, echo=FALSE}\n", # Here we're inserting a code chunk | |
"library(ggplot2) \n", | |
"myList$plot", # here we're outputting the plot we create below | |
"\n", | |
"```\n") | |
# This writes the content above to the specified filepath | |
write(content, rmd_file_name) | |
# now we render the markdown doc | |
rmarkdown::render(rmd_file_name) | |
utils::browseURL(paste0("file://", utils::URLencode(gsub("Rmd$", "html", rmd_file_name)))) | |
} | |
### MRE ### | |
# Some dummy analysis | |
df <- data.frame(x=rnorm(100,0,1), y=rnorm(100,0,1)) # generate data | |
plt <- ggplot(df, aes(x=x,y=y)) +geom_point() # create a plot | |
myList=list(plot=plt) # save the plot to a list object. If you were doing lots of analysis, you could create a list with all your plots and dfs | |
# Output with function | |
my_markdown_rederer(text,myList = myList) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment