简体   繁体   English

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

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

Is there a trick for captioning and referencing a chuck of code in rmarkdown (not the result of running the code)?是否有在 rmarkdown 中添加字幕和引用大量代码的技巧(不是运行代码的结果)? For example, how do I reference this block of code:例如,我如何引用这段代码:

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

I know that I can use \\@ref(fig:theFig) or \\@ref(tab:theTable) to get at fig.cap or caption (with kable) but I don't see a way to caption and reference the code itself.我知道我可以使用 \\@ref(fig:theFig) 或 \\@ref(tab:theTable) 来获取 fig.cap 或标题(使用 kable),但我看不到标题和引用代码本身的方法.

This would be a great feature.这将是一个很棒的功能。 And I think it is not integrated yet.而且我认为它还没有集成。 Here is an approach that works for PDF documents and allows you to generate captions as well as labels for cross-referencing:这是一种适用于 PDF 文档的方法,它允许您生成标题以及交叉引用的标签:

  1. Include a header.tex with the following content包含具有以下内容的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

Since the environment used for chunks is not a floating type we declare a new one, named chunk .由于用于块的环境不是浮动类型,我们声明了一个新的,名为chunk The option name is left blank since we already redefine \\thechunk in the next line by prepending the word Chunk (play with the name option and see what happens).选项name留空,因为我们已经在下一行中通过添加单词Chunk重新定义了\\thechunk (使用名称选项看看会发生什么)。

The chunks should be enumerated by section and so we tell tex to reset the counter each time a new section begins.块应该按部分枚举,因此我们告诉 tex 每次新部分开始时重置计数器。

If you do not use section numbering (by setting the YAML option), then replace the line如果您不使用节编号(通过设置 YAML 选项),则替换该行

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

by经过

\renewcommand{\thechunk}{Chunk~\arabic{chunk}}
  1. Modify the knitr source hook in your rmarkdown document修改你的 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)
})

Here we make use of two new chunk options ref and codecap .这里我们使用了两个新的块选项refcodecap If either one is not NULL , a corresponding label or caption is generated using the the commands \\label or \\captionof .如果其中一个不是NULL ,则使用命令\\label\\captionof生成相应的标签或标题。

MWE: 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}

Here is the output (of both pages):这是(两个页面的)输出:

在此处输入图片说明

在此处输入图片说明

Adding the caption below the code chunk在代码块下方添加标题

If you'd prefer to add the caption below the code chunk, instead of above, this can be achieved by altering the above knitr hook to read:如果您希望在代码块下方而不是上方添加标题,可以通过将上面的 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)
})

Comments:注释:

You could improve the code by checking what output type is desired so that the new source hook is only used for pdf output (skipped since it is lunch time).您可以通过检查所需的输出类型来改进代码,以便新的源挂钩仅用于 pdf 输出(由于是午餐时间而跳过)。

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

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