Skip to content

Instantly share code, notes, and snippets.

@thierrymoudiki
Last active October 27, 2024 07:09
Show Gist options
  • Save thierrymoudiki/4e8038f13ae1d67df6caf62e23a7c00d to your computer and use it in GitHub Desktop.
Save thierrymoudiki/4e8038f13ae1d67df6caf62e23a7c00d to your computer and use it in GitHub Desktop.
Makefile for working with Rmd and Rnw scripts
.PHONY: clean getwd initialize help render-rnw render-rmd setwd
.DEFAULT_GOAL := help
define BROWSER_PYSCRIPT
import os, webbrowser, sys
from urllib.request import pathname2url
# The input is expected to be the full HTML filename
filename = sys.argv[1]
filepath = os.path.abspath(os.path.join(filename))
webbrowser.open("file://" + pathname2url(filepath))
endef
export BROWSER_PYSCRIPT
define PRINT_HELP_PYSCRIPT
import re, sys
for line in sys.stdin:
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
if match:
target, help = match.groups()
print("%-20s %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT
BROWSER := python3 -c "$$BROWSER_PYSCRIPT"
clean: ## remove all build, and artifacts
rm -f .Rhistory
rm -f *.RData
rm -f *.Rproj
rm -rf .Rproj.user
getwd: ## get current directory
Rscript -e "getwd()"
initialize: setwd ## initialize: install packages devtools, usethis, pkgdown and rmarkdown
Rscript -e "utils::install.packages(c('devtools', 'rmarkdown', 'knitr'), repos='https://cloud.r-project.org')"
help: ## print menu with all options
@python3 -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
render-rnw: setwd ## run R Sweave file, open rendered file
@files=$$(ls -1 ./*.Rnw | sort); \
i=0; \
echo "Available Rnw files:"; \
for file in $$files; do \
echo "$$i: $$(basename $$file .Rnw)"; \
i=$$((i+1)); \
done; \
read -p "Enter the number of the Rnw file to render: " filenum; \
filename=$$(echo $$files | cut -d' ' -f$$((filenum+1))); \
filename=$$(basename $$filename .Rnw); \
rm -f $$filename.pdf || true; \
Rscript -e "require('knitr'); knitr::knit2pdf(paste0('$$filename', '.Rnw'))"; \
python3 -c "$$BROWSER_PYSCRIPT" "$$filename.pdf"
render-rmd: setwd ## run R markdown file, open rendered file
@files=$$(ls -1 ./*.Rmd | sort); \
i=0; \
echo "Available Rmd files:"; \
for file in $$files; do \
echo "$$i: $$(basename $$file .Rmd)"; \
i=$$((i+1)); \
done; \
read -p "Enter the number of the Rmd file to render: " filenum; \
filename=$$(echo $$files | cut -d' ' -f$$((filenum+1))); \
filename=$$(basename $$filename .Rmd); \
rm -f $$filename.pdf || true; \
Rscript -e "rmarkdown::render(paste0('$$filename', '.Rmd'))"; \
python3 -c "$$BROWSER_PYSCRIPT" "$$filename.pdf"
setwd: ## set working directory to current directory
Rscript -e "setwd('.')"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment