Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)}
```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading