繁体   English   中英

rmarkdown 是否允许代码块的标题和引用?

[英]Does rmarkdown allow captions and references for code chunks?

是否有在 rmarkdown 中添加字幕和引用大量代码的技巧(不是运行代码的结果)? 例如,我如何引用这段代码:

```{r blah}
blah <- "blah"
```

我知道我可以使用 \\@ref(fig:theFig) 或 \\@ref(tab:theTable) 来获取 fig.cap 或标题(使用 kable),但我看不到标题和引用代码本身的方法.

这将是一个很棒的功能。 而且我认为它还没有集成。 这是一种适用于 PDF 文档的方法,它允许您生成标题以及交叉引用的标签:

  1. 包含具有以下内容的header.tex

\usepackage{caption}
\usepackage{floatrow}

\DeclareNewFloatType{chunk}{placement=H, fileext=chk, name=}
\captionsetup{options=chunk}
\renewcommand{\thechunk}{Chunk~\thesection.\arabic{chunk}}
\makeatletter
\@addtoreset{chunk}{section}
\makeatother

由于用于块的环境不是浮动类型,我们声明了一个新的,名为chunk 选项name留空,因为我们已经在下一行中通过添加单词Chunk重新定义了\\thechunk (使用名称选项看看会发生什么)。

块应该按部分枚举,因此我们告诉 tex 每次新部分开始时重置计数器。

如果您不使用节编号(通过设置 YAML 选项),则替换该行

\renewcommand{\thechunk}{Chunk~\thesection.\arabic{chunk}}

经过

\renewcommand{\thechunk}{Chunk~\arabic{chunk}}
  1. 修改你的 rmarkdown 文档中的 knitr source hook

library(knitr)
oldSource <- knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
  x <- oldSource(x, options)
  x <- ifelse(!is.null(options$ref), paste0("\\label{", options$ref,"}", x), x)
  ifelse(!is.null(options$codecap), paste0("\\captionof{chunk}{", options$codecap,"}", x), x)
})

这里我们使用了两个新的块选项refcodecap 如果其中一个不是NULL ,则使用命令\\label\\captionof生成相应的标签或标题。

MWE:

---
title: "Cross-referencing Code Chunks"
output: 
  pdf_document: 
    includes:
      in_header: header.tex
    number_sections: true
---

```{r, echo=FALSE}
library(knitr)
oldSource <- knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
  x <- oldSource(x, options)
  x <- ifelse(!is.null(options$ref), paste0("\\label{", options$ref,"}", x), x)
  ifelse(!is.null(options$codecap), paste0("\\captionof{chunk}{", options$codecap,"}", x), x)
})
```

# Foo

Jump to \ref{TheBarChunk}

```{r Foo, ref = "TheFooChunk", codecap = "My Chunk"}
print("Foo!")
```

\newpage

# Bar

```{r Bar, ref = "TheBarChunk", codecap = "My second chunk"}
print("Bar!")
```

Head back to \ref{TheFooChunk}

这是(两个页面的)输出:

在此处输入图片说明

在此处输入图片说明

在代码块下方添加标题

如果您希望在代码块下方而不是上方添加标题,可以通过将上面的 knitr 钩子更改为读取来实现:

oldSource <- knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
  x <- oldSource(x, options)
  x <- ifelse(!is.null(options$codecap), paste0(x, "\\captionof{chunk}{", options$codecap,"}"), x)
  ifelse(!is.null(options$ref), paste0(x, "\\label{", options$ref,"}"), x)
})

注释:

您可以通过检查所需的输出类型来改进代码,以便新的源挂钩仅用于 pdf 输出(由于是午餐时间而跳过)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM