Search code examples
rr-markdownknitr

Show specific lines from a file using knitr/rmarkdown


The problem

Let's say I have script.R that contains:

x <- data.frame(
    a = 1:10,
    b = 11:20
)

y <- rnorm(100)

I want to just show the first 4 lines that relate to x, in a chunk of an RMarkdown document.


Things I've tried

  • {R, file = "script.R"} as a knitr option will include the entire file, which I don't want
  • {R, code = xfun::read_all("script.R")[1:4]} does let me subset the file, but it prints the result as an R vector with line numbers, rather than formatting it as source code
  • The following hack does mostly work. It manually builds the markdown string. However, I find it very complex and messy, and I'm hoping for a better solution:
    ```{R, results="asis"}
    readLines("test.R")[1:4] |>
    c("```{r}", content=_, "```") |>
    paste(collapse = "\n") |>
    cat()
    
  • Using read_chunk. This should work, but I dislike having to have two chunks when I only want one:
    ```{r, include=FALSE, cache=FALSE}
    knitr::read_chunk('script.R', labels="chunk-a", from=1, to=4)
    ```
    ```{r, chunk-a}
    ```
    

Solution

  • Is this what you want?

    ```{r, code = readLines("test.R")[1:4]}
    ```
    

    Edit

    Or maybe this is cleaner:

    ```{r, code = readLines("test.R", n = 4)}
    ```