【发布时间】:2025-12-06 01:05:02
【问题描述】:
我正在使用knitr 来编织 RMarkdown,我曾多次想以编程方式添加代码块,但未能找到令人满意的方法。假设我想让knitr 在文件完成编织时播放声音。我解决这个问题的方法是这样的:
beep_on_knit <- function(beep_sound=3, sleep=3) {
library(beepr)
last_label <- tail(knitr::all_labels(),n=1)[[1]]
knitr::knit_hooks$set(
.beep_on_last_chunk =
function(before, options) {
if (options$label == last_label & !before) {
beepr::beep(beep_sound)
Sys.sleep(sleep)
invisible(NULL)
}
})
# Sets the options for every chunk so the hook will be run on them
knitr::opts_chunk$set(.beep_on_last_chunk = TRUE)
}
但是,必须编辑每个块的块属性(即knitr::opts_chunk$set(.beep_on_last_chunk = TRUE) 意味着如果我将此函数添加到文档中,它将使以前缓存的每个块的缓存无效。
有没有办法预先设置特定块的选项?
【问题讨论】:
标签: r r-markdown knitr chunks