79600119

Date: 2025-04-30 10:28:43
Score: 1
Natty:
Report link

For those interested, here is a sample program, and the final custom function. (save as custom-knit.r)

custom_knit <- (function(input, ...) {
# Initial version from multiple sites/contributors:
# https://stackoverflow.com/questions/79595316/knit-once-save-twice
# https://stackoverflow.com/questions/66620582/customize-the-knit-button-with-source
    
# parameters for rendering: set to none to ignore
# suffix: 
#   date (rmd name + YYYYMMDD.html, 
#   datetime (rmd name + YYYYMMDD-YYMMSS.html)
#   none (just rmd name) ]
#
# readme: 
#   path/filename (e.g., /Production/_Readme-StatAreas2022)
#   filename      (e.g., _Readme-IndustryHazards)
#   none (no additional simply named document created)
     
# read Rmd yaml into R object
yaml <- rmarkdown::yaml_front_matter(input)
    
# Rmd file name without path or extension
    rmd_basename <- tools::file_path_sans_ext(basename(input))
    
    # Suffix creation for complex name
    if (yaml$params$suffix=="date") {
      complex_name <- paste0(rmd_basename, '-', format(Sys.time(), "%Y%m%d"), '.html')
    } else if (yaml$params$suffix=="datetime") {
      complex_name <- paste0(rmd_basename, '-', format(Sys.time(), "%Y%m%d-%H%M%S"), '.html')
    } else {
      complex_name <- paste0(rmd_basename, '.html')
    }
    
    # render Rmd file and record absolute path to output file
    complex_path <- rmarkdown::render(
      input,
      output_file = complex_name, 
      output_dir = "Output", 
      envir = globalenv()
    )
    
    # Process additional copy if requested
    simple_path  <- yaml$params$simple
    
    # perform copy
    if (yaml$params$simple!="none") {
      simple_path <- paste0(simple_path,'.html')
      file.copy(complex_path, simple_path, overwrite=TRUE)
    }
})

Here is the YAML section

---
title: "RenderExample - Custom knit"
subtitle: "see params"
author: "Mark Friedman"
date: "`r format(Sys.time(), '%d %B, %Y %H:%M')`"
output: html_document 
    
params:
  suffix: datetime # date, datetime, none
  simple: Production/_Readme-Stat2022 # path+base, base only, none

knit: (function(input, ...) {
    source("custom-knit.R");
    custom_knit(input, ...)
  })

---
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Mark Friedman