Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute all R chunks at once from an Rmd document

A minimal Rmarkdown document has a YAML header, markdown syntax and R code chunks. To edit such a multi-language file, I am using the Emacs editor, and the buffer in which the Rmd document is opened, is in polymode.

A typical document has more than one R chunk. When I am writing/debugging an R chunk in the middle of the Rmd document, I have a second buffer in the ESS mode with R running inside, and I often have to re-execute all previous chunks by sending the R commands from the Rmd file (1st buffer) into the into R console (2nd buffer).

Is there a single command allowing to execute all commands from all chunks?

From another question, it seems like org-mode can do this. But would it be possible to do it in my setting?

like image 630
tflutre Avatar asked Nov 30 '16 17:11

tflutre


People also ask

How do I run all chunks in R?

Run all chunks with Command + Option + R or Command + A + Enter on a Mac; Ctrl + Alt + R or Ctrl + A + Enter on Linux and Windows.

How do you expand all chunks in R?

Expand All — Shift+Alt+O.


2 Answers

If using Poly-Markdown+R, the command to evaluate all R snippets in an Rmarkdown document is M-n v b.

Reference

like image 104
DomQ Avatar answered Sep 18 '22 00:09

DomQ


If you only have R source code in your Rmarkdown, and want to be able to interactively evaluate it easily, spin from knitr might be easier (see here).

I prefer that (spin) solution, since all the markdown/Rmarkdown mumbo-jumbo is contained within normal R comments, so the buffer can be treated like regular source code. But, the following should evaluate all the R code chunks in a polymode buffer (not tested thoroughly).

(eval-when-compile
  (require 'polymode-core)  ;; SO format :('
  (defvar pm/chunkmode))
(declare-function pm-map-over-spans "polymode-core")
(declare-function pm-narrow-to-span "polymode-core")

(defun rmd-send-chunk ()
  "Send current R chunk to ess process."
  (interactive)
  (and (eq (oref pm/chunkmode :mode) 'r-mode) ;;'
       (pm-with-narrowed-to-span nil
         (goto-char (point-min))
         (forward-line)
         (ess-eval-region (point) (point-max) nil nil 'R)))) ;;'

(defun rmd-send-buffer (arg)
  "Send all R code blocks in buffer to ess process. With prefix
send regions above point."
  (interactive "P")
  (save-restriction
    (widen)
    (save-excursion
      (pm-map-over-spans
       'rmd-send-chunk (point-min) ;;'
       ;; adjust this point to send prior regions
       (if arg (point) (point-max))))))
like image 43
Rorschach Avatar answered Sep 19 '22 00:09

Rorschach