You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将一个Rmarkdown文档中的代码块插入到另一个文档中?

Nice question—this is exactly the kind of workflow that keeps workshop materials maintainable instead of copying and pasting everything! Here are a few reliable methods to insert code blocks from one RMarkdown document into another, tailored to your workshop use case:

This approach relies on labeling code blocks in your source document (e.g., the challenge Rmd) so you can pull specific blocks directly into your target document (e.g., the solution Rmd).

Steps:

  1. Label code blocks in your challenge Rmd
    Give each fill-in-the-blank code block a unique label in its chunk header. For example:

    # Workshop Challenge: Explore mtcars
    Calculate the average MPG for each cylinder group.
    
    ```{r calculate-mean-mpg, echo=TRUE}
    # Your code here: Use dplyr's group_by() and summarize()
    
    The `calculate-mean-mpg` label is what we'll use to target this block later.
    
    
  2. Read the labeled chunk in your solution Rmd
    Add a setup chunk at the top of your solution document to pull in the code block from the challenge Rmd:

    # Pull the specific labeled chunk from the challenge document
    knitr::read_chunk("challenge_workshop.Rmd", labels = "calculate-mean-mpg")
    
  3. Insert and populate the chunk
    In the solution Rmd, call the labeled chunk and replace the placeholder with your completed code:

    # Workshop Solution: Explore mtcars
    Calculate the average MPG for each cylinder group.
    
    ```{r calculate-mean-mpg, echo=TRUE}
    # Here's the completed code:
    library(dplyr)
    mtcars %>%
      group_by(cyl) %>%
      summarize(mean_mpg = mean(mpg))
    
    Pro tip: If you want to show both the challenge placeholder and the solution, you can call the original chunk first, then add a new chunk with the completed code.
    
    

Method 2: Extract All Code to a Script with knitr::purl()

If you don't want to label every chunk, you can convert your entire challenge Rmd into a pure R script, then pull specific sections from that script.

Steps:

  1. Convert challenge Rmd to an R script
    In your solution Rmd's setup chunk, run:

    # Extract only code blocks from the challenge Rmd (no text comments)
    knitr::purl("challenge_workshop.Rmd", output = "challenge_scripts.R", documentation = 0)
    
  2. Label sections in the generated script
    Go back to your challenge Rmd and add comment labels above code blocks you want to target, like:

    # ---- calculate-mean-mpg ----
    ```{r echo=TRUE}
    # Your code here...
    
    These comments will carry over to the R script, making it easy to pull specific sections.
    
    
  3. Read and insert the script section
    Use read_chunk() on the R script, then call the label just like in Method 1.

Method 3: Flexible Extraction with Regular Expressions

For full control (e.g., modifying code before inserting), you can read the raw Rmd content and extract code blocks with regex.

Example:

```{r extract-code, include=FALSE}
library(xfun)
# Read the full challenge Rmd content
rmd_content <- read_utf8("challenge_workshop.Rmd")
# Match the specific code block using its label
code_match <- regexpr(
  "(?<=```\\{r calculate-mean-mpg.*?\\}\\n)(.*?)(?=```)",
  paste(rmd_content, collapse = "\n"),
  perl = TRUE
)
# Extract the placeholder code
challenge_code <- regmatches(paste(rmd_content, collapse = "\n"), code_match)
# Generate the solution code by replacing the placeholder
solution_code <- gsub("# Your code here: ", "", challenge_code) %>%
  paste("library(dplyr)\nmtcars %>%\n  group_by(cyl) %>%\n  summarize(mean_mpg = mean(mpg))", sep = "\n")
Workshop Solution: Explore mtcars

Calculate the average MPG for each cylinder group.

`r solution_code`
## Bonus: Keep Text Content Synced
To avoid duplicating plain text between challenge and solution docs, store all shared text in a separate `common_content.Rmd` file, then import it into both documents with:
```{r include-common, echo=FALSE}
knitr::knit_child("common_content.Rmd", output = TRUE)

内容的提问来源于stack exchange,提问作者Russ Hyde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:00:07