Last active
July 27, 2020 12:50
-
-
Save eddjberry/d2918b05b9f12e24db46167b675b9e1f to your computer and use it in GitHub Desktop.
Knit a directory of files from the command line
This file contains 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
#!/usr/bin/env Rscript | |
# to run from command line: | |
## chmod +x knit_dir.R | |
## ./knit_dir.R <dir-name> | |
# from https://stackoverflow.com/a/49950761 | |
# to avoid conflicts between packages | |
# breaking things | |
clean_search <- function() { | |
defaults <- c(".GlobalEnv", | |
paste0("package:", getOption("defaultPackages")), | |
"Autoloads", | |
"package:base") | |
currentList <- search() | |
deletes <- setdiff(currentList, defaults) | |
for (entry in deletes) | |
detach(entry, character.only = TRUE) | |
} | |
# function to knit directory | |
knit_dir <- function(dir) { | |
# create the full path | |
full_dir <- normalizePath(dir) | |
# list the Rmd files with full names | |
files <- | |
list.files(full_dir, pattern = '*.Rmd$', full.names = TRUE) | |
# render the files using all output formats in the YAML | |
purrr::map(files, function(file) { | |
# clean search list to avoid conflicts | |
clean_search() | |
# render the file using all | |
# output formats in a new env | |
rmarkdown::render(file, | |
output_format = "all", | |
envir = new.env()) | |
}) | |
} | |
# pull out the first command line argument | |
dir <- commandArgs(trailingOnly = TRUE)[1] | |
# run the function | |
knit_dir(dir) |
Have added the cleanSearch()
function from https://stackoverflow.com/a/49950761 to fix conflicts between packages
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad that the comments were helpful! On second thought
parent = emptyenv()
is certainly way too conservative!