Skip to content

Instantly share code, notes, and snippets.

@eddjberry
Last active July 27, 2020 12:50
Show Gist options
  • Save eddjberry/d2918b05b9f12e24db46167b675b9e1f to your computer and use it in GitHub Desktop.
Save eddjberry/d2918b05b9f12e24db46167b675b9e1f to your computer and use it in GitHub Desktop.
Knit a directory of files from the command line
#!/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)
@eddjberry
Copy link
Author

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