Search code examples
r-markdownknitrbookdown

With R markdown, is it possible to change the format of the first reference to a display item?


Some journals requires that the first reference to a display item should be bold, but from the second one onward the normal format would be used. Basically:

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...

Is it possible to realize in R markdown? More specifically, is it possible with bookdown::word_document2?


Solution

  • I doubt there is any built in functionality for this. The idea being that you would manage it yourself by denoting each initial reference with bold markdown (i.e., **Figure 1**).

    But you might accomplish this automatically with something like a custom knitr hook or maybe even a lua filter to process the document during document render.

    Here is an example of a custom knitr output hook:

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