knitr icon indicating copy to clipboard operation
knitr copied to clipboard

read_chunk() could support reading Rmd and use chunk label

Open cderv opened this issue 3 years ago • 1 comments

I am opening this here to not forget. It is possibly opened elsewhere but I did not find it.

This is something that could be useful and see asked already for example in the community https://community.rstudio.com/t/use-chunk-labels-from-rmarkdown-with-knitr-read-chunk/106243

read_chunk() could read an R file and parse special comment. (https://bookdown.org/yihui/rmarkdown-cookbook/read-chunk.html)

It could be interesting to be able to read an Rmd file and do the same but with chunk label and chunk content.

Not sure how difficult it would be. Just throwing the idea.

cderv avatar Sep 01 '21 16:09 cderv

This is possible with purl. However, I would not encourage such a use case for some reasons:

  • The chunk may not do the same in case chunk has some dependencies (variables, packages, and so on)
  • In collaborative projects, it is difficult for members to guess which chunk is used by the other files.

I think the ideal way is to split the source code into a function in an R script.

knitr::knit(
  text = c(
    "```{r foo}", "1", "```",
    "",
    "```{r bar}", "2", "```"
  ),
  tangle = TRUE,
  quiet = TRUE
) |>
  stringr::str_split("\n") |>
  (function(x) knitr::read_chunk(lines = x[[1]]))()
knitr::knit_code$get("foo")
#> [1] "1"

Created on 2021-09-26 by the reprex package (v2.0.1)

atusy avatar Sep 26 '21 11:09 atusy