如何使用Emacs、ESS、pandoc-mode和polymode从Rmd文件创建PDF?

17

这是一个“经典”的Rmd文件的改编,我想使用Emacs(Emacs Speak Statistics)和polymode将其编织为pdf。我找不到正确的命令来做到这一点。polymode的文档很少。我正在使用社会科学的Emacs入门套件

---
title: "Untitled"
author: "SB"
date: "Wednesday, February 04, 2015"
output: pdf_document
---

You can embed an R code chunk like this:

```{r}
summary(cars)
```

You can also embed plots, for example:

```{r, echo=FALSE}
plot(cars)
```
2个回答

11

根据文档,使用M-n wM-n W 来设置/更改编织器。如果您正在使用 ESS,则应使用knitr-ESS编织器,因为它使用当前的*R*进程。


1
文件名为 _sb_ex.Rmd_。我使用 M-n W 选择了 knitr-ESS,然后使用 M-n w,但结果出现错误:> library(knitr); knit('sb_ex.Rmd', output='sb_ex[weaved].md') Error in library(knitr) : there is no package called 'knitr' - sbac
1
它在Windows上无法工作,但在Mac OSX上可以。唯一的问题是,当我尝试使用M-n e来使用_pandoc_导出pdf时,我无法看到pdf格式作为选项。然后我使用_emacs菜单_中的_pandoc-mode_创建pdf。 - sbac
1
@博士,您需要安装pandoc才能使其正常工作。如果无法正常工作,请转到“polymode weave”缓冲区。如果有任何pandoc错误,它应该会显示出来。 - VitoshKa
类似于sbac的问题 - 当我使用M-n e时,pdf文件无法显示 - ilya
这个答案对我很有帮助,但我发现这个编织工具实际上被命名为knitR-ESS - ericOss
显示剩余3条评论

5
你可以使用 rmarkdown软件包 中的rmarkdown::render(),只需一个命令就可以将.Rmd文件编织成标记并渲染输出文件(PDF,Word,HTML等)! 我不确定ESS是否已经支持rmarkdown工作流程(我正在尝试涉足elisp),所以我编写了一个函数来调用rmarkdown::render()和允许自定义输入到rmarkdown::render()函数调用的前缀参数(例如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)

请注意,我有一些特定的参数设置,如output_dir = '../reports',但elisp可以轻松自定义以适应您的需求。
将此代码添加到您的init文件中后,只需从您的.Rmd文件内部输入C-c r(或者 C-u C-c r以渲染到不同的格式、位置等)即可。该命令将打开一个名为*compilation*的缓冲区的新窗口,在其中任何错误都会出现。
这肯定可以改进,我很乐意听取建议。

所以我喜欢这个概念,但它对我不起作用,而且我是一个糟糕的elisp程序员。在我看来,问题似乎是命令被用双引号发送到R中,因此R将其解释为字符串文字。(我在Windows上) - mac
确实。引号是我机器上的问题。通过编辑您代码中的一行进行修复,现在为:(setq command (concat "echo " rcmd " | R --vanilla")) - mac
1
对于未来的读者而言,如果您不需要太多自定义设置,使用 polymode 的内置功能将更加简单。使用 M-n E 来选择导出器,使用 M-n e 将 R Markdown 文档导出到所需的格式。 - Stefan Avey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接