'How to call R Markdown knit function from Python script
I have a Python script that creates multiple .Rmd files, and I wanted a way to automatically turn them into .html's without having to manually knit each within RStudio. I've probably spent around 4 hours researching and trying different options, and although I've managed to make it work by calling a .R script with
subprocess.Popen(['Rscript', '--vanilla', 'rmd2html.R'], shell=False)
that then does the knitting with
rmarkdown::render("dicionarioNew.Rmd", "html_document"),
this for some reason does not use UTF-8 (which I need) and doesn't easily allow me to store the number of times the program has been run (necessary for giving a different name to each html file).
Solution 1:[1]
Your title question is answered in your question's body but you have more specific needs not met by your current implmentation:
- how to render .Rmd using UTF-8
- how to render .Rmd to html with custom filename output
I suggest you try seeking out the answers to these individually.
As a general answer to this question however, I suggest you consider using the Rscript command to run a custom R script which does what you want based on the source of rmd2html.R. You might also use R -e to execute a line or few of R code hardcoded as a string in your python script.
If you want to break things out further in python, there are many options for rendering at the chunk or file level individually using the sweave, rmarkdown, stationary, and other R packages. Given a more specific example of what you are trying to accomplish someone may be able to help point you towards which of these many options would be right for your use case.
Solution 2:[2]
An alternative is to add a chunk that will knit the .rmd file when it is executed. See my approach below - it also opens the .html file in the view panel of Rstudio after knitting. That way you can probably also build in the tracker of how many times the code is run and add that into the file-name.
For the "auto_knit_chunk" shown below to work you need to setup two variables, KNITreport (TRUE/FALSE) and the output directory (or remove their use if you don't need them) in a chuck above the "auto_knit_chunk".
#IN A CHUNK ABOVE THE auto_knit_chunk SET THE VARIABLES
#if this RMD file should be knitted, set KINITreport = TRUE
KNITreport <- TRUE
#set an output path
dir_output <- "./output/"
The "auto_knit_chunk" chunk should only be executed IF knitr is not currently executed to avoid an infinite loop of calling knitr from each document that is knitted. So in the header do: eval = !=isTRUE(getOption('knitr.in.progress'))
# THIS IS THE HEADER ```{r, auto_knit_chunk, echo = FALSE, eval = !isTRUE(getOption('knitr.in.progress'))}
if(KNITreport)
{
#saving the currently open Rstudio file - needs to be saved bevore knitting to knit the most up to date version
rstudioapi::documentSave(rstudioapi::getActiveDocumentContext()$id)
#obtaining the file name of the currently active document
RMD_fileName <- str_replace(rstudioapi::getActiveDocumentContext()$path, paste0(sub("\\/[^\\/]*$", "",rstudioapi::getActiveDocumentContext()$path),"/"),"")
#setting up the file name and output directory to save the knitted file
outputFileName <- paste0(str_replace(RMD_fileName,".Rmd",""), "_KNITTED")
outputPath <- paste0(getwd(),str_replace(dir_output,".",""))
#if there is an RMD_fileName knit it
if(RMD_fileName!=""){
rmarkdown::render(input = RMD_fileName, output_file = outputFileName, output_dir = outputPath)
print(paste("Summary file:",outputFileName," is at",outputPath))
}else print("No RMD file retrieved")
#a function to display HTML content in the Rstudio viewer
viewerpane.html <- function(xfile, vsize=NULL){
# viewerpane.html was written by anwhite03 and published here:
# https://community.rstudio.com/t/rstudio-knit-explicit-r-command-for-preview-option-after-rmd-is-knit/11368
# Function: viewerpane.html version 1.00 23July2018
# Purpose: view RMarkdown Knit-generated html file in RStudio Viewer pane
# Status: Dev/Test
# Args:
# xfile = quoted name of html file (and path if not located in current directory)
# vsize = viewer arg height, default=NULL; alt values: "maximize", or numeric {3 to 8}
# Example: x <- "RMD-Demo-Viridis-002x.html"
# References:
# 1. https://rstudio.github.io/rstudio-extensions/rstudio_viewer.html
# 2. https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html
# 3. https://rstudio.github.io/rstudio-extensions/rstudioapi.html
#
# library(rstudioapi)
xfile.b <- basename(xfile)
tempDir <- tempfile()
dir.create(tempDir)
htmlFile <- file.path(tempDir, xfile.b)
# (code to write some content to the file) -- see next line
file.copy(xfile, htmlFile)
viewer <- getOption("viewer")
viewer(htmlFile, height = vsize)
}
#calling the function to display the HTML document
viewerpane.html(xfile = paste0(outputPath,outputFileName,".html"))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 7yl4r |
| Solution 2 |
