使用 R markdown,是否可以更改显示项的第一个引用的格式?

问题描述 投票:0回答:1

有些期刊要求对显示项目的第一个引用应为粗体,但从第二个引用开始将使用正常格式。基本上:

图 1 显示了我们惊人的结果。 图2也很重要。不过,需要注意的是,与图1不同的是,图2中使用的方法发生了变化......

可以在R markdown中实现吗?更具体地说,可以用

bookdown::word_document2
吗?

r-markdown knitr bookdown
1个回答
0
投票

我怀疑是否有任何内置功能。这个想法是,您可以通过用粗体标记表示每个初始引用(即

**Figure 1**
)来自行管理它。

但是您可以使用自定义knitr hook 之类的东西自动完成此操作,甚至可以使用 lua 过滤器在文档渲染期间处理文档。

以下是自定义 knitr 输出钩子的示例:

---
title: "Custom Knitr Document Output Hook"
output: bookdown::word_document2
date: "2024-04-25"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

local({
  hook_old <- knitr::knit_hooks$get("document") 
  knitr::knit_hooks$set(document = function(x) {
    # previously observed figure references
    obs_fig_refs <- character(0)
    
    # seq along the knitr outputs consisting of the yaml, chunks, and text
    for(i in seq_along(x)) {
      # if current output is text
      if(stringr::str_detect(x[i], "(---|```)", negate = TRUE)) {
        # extract the unique figure references
        fig_refs <- unique(stringr::str_extract_all(x[i], "Figure \\d+")[[1]])
        
        # seq along the unique figure references
        for(j in seq_along(fig_refs)) {
          # if this reference has not been previously observed
          if(!(fig_refs[j] %in% obs_fig_refs)) {
            # remember it has been observed
            obs_fig_refs <- c(obs_fig_refs, fig_refs[j])
            # and make the first reference bold
            x[i] <- stringr::str_replace(
              x[i], 
              fig_refs[j], 
              sprintf("**%s**", fig_refs[j])
            )
          }
        }
      }
    }
    hook_old(x)
  })
})
```

Figure 1 showed our amazing results. Figure 2 is also important. However, it should be noted that unlike Figure 1, the method used in Figure 2 had changed...

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.