簡體   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