kbc
kbc

Reputation: 61

Customize the Knit button with source

The rmarkdown's documentation , recommends customising knitr button with custom script called via source.

This is the YAML of .Rmd file

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

My approach

I have created a custom-function.R script in the same directory and tried to call via source.

custom-function.R

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

.Rmd file

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

The error is -

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

Looks like there is syntax error. I checked the documentation of source and syntax looks fine.

What am I doing wrong here?

Upvotes: 0

Views: 280

Answers (1)

Zhenya K.
Zhenya K.

Reputation: 345

I don't think the documentation you linked to mentions using the source function at all. It might have changed since you asked the question, but right now it only mentions two options:

  • "write the source code of the function directly in the knit field"
  • "put the function elsewhere (e.g., in an R package) and call the function in the knit field"

I guess your situation is a little bit of both. Here is what you can do:

In custom-function.R name the function (no need for parentheses here):

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

Then, in your .rmd file, write another function that first sources the script above and then calls the custom_knit function. Here, you do need parentheses. Also, "if the source code has multiple lines, you have to indent all lines (except the first line) by at least two spaces" (from the bookdown docs you linked to).

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

Upvotes: 3

Related Questions