使用源自定义编织按钮

Customize the Knit button with source

rmarkdown 的 documentation,建议使用通过源调用的自定义脚本自定义 knitr 按钮。

这是 .Rmd 文件的 YAML

---
knit: (function(input, ...) {
    # my custom commands
  })
---

我的做法

我在同一目录中创建了一个 custom-function.R 脚本并尝试通过源调用。

custom-function.R

(function(input, ...) {
        # my custom commands
      })

.Rmd 文件

---
knit: source("custom-function.R")
---

错误是-

Error: unexpected symbol in "(function(input, ...) { system(paste0("source("custom-function.R"
Execution halted

看起来有语法错误。我检查了 documentation of source,语法看起来不错。

我做错了什么?

我认为您链接到的文档根本没有提到使用 source 函数。自从你问这个问题后它可能已经改变了,但现在它只提到两个选项:

  • "直接在knit字段中写入函数的源代码"
  • “将函数放在别处(例如,在 R 包中)并在 knit field 中调用函数”

我猜你的情况是两者兼而有之。您可以执行以下操作:

custom-function.R中命名函数(这里不需要括号):

custom_knit <- function(input, ...) {
  # your custom commands
  # don't forget to actually call `rmarkdown::render()`
}

然后,在您的 .rmd 文件中,编写另一个函数,该函数首先获取上面的脚本,然后调用 custom_knit 函数。在这里,你 do 需要括号。此外,“如果源代码有多行,则必须将所有行(第一行除外)缩进至少两个空格”(来自您链接到的 bookdown 文档)。

knit: (function(input, ...) {
    source("custom-function.R");
    custom_knit(input, ...)
  })