Render R markdown to PDF from command line
I have been using Makefiles where command line tools for building a project are not generally available. This includes LaTeX documents and recently R projects.
So here is an R script that can be used to render R markdown to PDF.
It will process Rmd files listed after the --args parameter. This script can then be invoked from Makefile:
#!/usr/bin/env R # Render R markdown to PDF. # Invoke with: # > R -q -f make.R --args my_report.Rmd # load packages require(rmarkdown) # require a parameter naming file to render if (length(args) == 0) { stop("Error: missing file operand", call. = TRUE) } else { # read report to render from command line for (rmd in commandArgs(trailingOnly = TRUE)) { # render Rmd to PDF if ( grepl("\\.Rmd$", rmd) && file.exists(rmd)) { render(rmd, pdf_document()) } else { print(paste("Ignoring: ", rmd)) } } }
It will process Rmd files listed after the --args parameter. This script can then be invoked from Makefile:
#!/usr/bin/env make .PHONY: all clean .SUFFIXES: .Rmd .pdf DOCS = my-report RMDS = $(patsubst %, %.Rmd, $(DOCS)) R = /usr/bin/R Rmd: $(patsubst %.Rmd, %.pdf, $(RMDS)) .Rmd.pdf: @$(R) --quiet --file=make.R --args $< all: clean Rmd clean: @rm -f $(patsubst %.Rmd, %.pdf, $(RMDS))
No comments:
Post a Comment