You can use rmarkdown::render()
from the rmarkdown package to knit an .Rmd
file to markdown and render the output file (PDF, Word, HTML, etc.) with a single command!
I wasn't sure if support for an rmarkdown
workflow was already included in ESS (and I'm trying to dabble in elisp) so I wrote a function that calls rmarkdown::render()
and allows customizing the inputs to rmarkdown::render()
function call with a prefix arg (e.g., C-u
).
;; spa/rmd-render
;; Global history list allows Emacs to "remember" the last
;; render commands and propose as suggestions in the minibuffer.
(defvar rmd-render-history nil "History list for spa/rmd-render.")
(defun spa/rmd-render (arg)
"Render the current Rmd file to PDF output.
With a prefix arg, edit the R command in the minibuffer"
(interactive "P")
;; Build the default R render command
(setq rcmd (concat "rmarkdown::render('" buffer-file-name "',"
"output_dir = '../reports',"
"output_format = 'pdf_document')"))
;; Check for prefix argument
(if arg
(progn
;; Use last command as the default (if non-nil)
(setq prev-history (car rmd-render-history))
(if prev-history
(setq rcmd prev-history)
nil)
;; Allow the user to modify rcmd
(setq rcmd
(read-from-minibuffer "Run: " rcmd nil nil 'rmd-render-history))
)
;; With no prefix arg, add default rcmd to history
(setq rmd-render-history (add-to-history 'rmd-render-history rcmd)))
;; Build and evaluate the shell command
(setq command (concat "echo \"" rcmd "\" | R --vanilla"))
(compile command))
(define-key polymode-mode-map (kbd "C-c r") 'spa/rmd-render)
Note that I have some specific parameter settings like output_dir = '../reports'
but the elisp can be easily customized to suit your needs.
With this in your init file, you only need to enter C-c r
from inside your .Rmd
file (or C-u C-c r
to render to a different format, location, etc.). The command will open a new window with a buffer called *compilation*
where any errors will appear.
This could definitely be improved and I'd love to hear suggestions.
> library(knitr); knit('sb_ex.Rmd', output='sb_ex[weaved].md') Error in library(knitr) : there is no package called 'knitr'
– Nanete