使用knitr::purl的块引用

使用knitr::purl的块引用,r,knitr,R,Knitr,在我看来,knitr::purl似乎不处理块引用。见例 cat(' ```{r label, eval = FALSE} print("Second: hello world!") ``` This is first. ```{r ref.label = "label", echo = FALSE} ``` ', file = "test.Rmd") 现在我们用knit和purl来处理这个问题 knitr::knit("test.Rmd", "test.md") knitr::purl("

在我看来,
knitr::purl
似乎不处理块引用。见例

cat('
```{r label, eval = FALSE}
print("Second: hello world!")
```

This is first.

```{r ref.label = "label", echo = FALSE}
```
', file = "test.Rmd")
现在我们用
knit
purl
来处理这个问题

knitr::knit("test.Rmd", "test.md")
knitr::purl("test.Rmd", "test.R")

cat(readLines("test.md"), sep = "\n")

#> ```r
#> print("Second: hello world!")
#> ```
#>
#> This is first.
#>
#>
#> ```
#> ## [1] "Second: hello world!"
#> ```

cat(readLines("test.R"), sep = "\n")

#> ## ----label, eval = FALSE---------------------------------------------
#> ## print("Second: hello world!")
#>
#> ## ----ref.label = "label", echo = FALSE-------------------------------
#>
我不完全确定
echo=FALSE
对于
purl
意味着什么,但是
echo=TRUE
也不起作用
purl=TRUE
和/或
eval=TRUE
也会产生相同的结果


我是不是误解了什么?
purl
不应该只输出运行
knit
的代码吗?

以下是我的解决方法。对于我不想运行但想包含在
.html
.R
输出中的块,我指定了
purl=TRUE
,例如

```{r label, eval = FALSE, purl = TRUE}
server <- function(input, output, session) {
  rvs <- reactiveValues(data = NULL)
  # ...
}
```
然后使用此后处理功能取消注释具有
purl=TRUE
的部分:

postprocess <- function(file) {

  lines <- readLines(file)

  include <- grep("^## ---.*purl = TRUE.*$", lines)
  empty <- grep("^\\s*$", lines, perl = TRUE)

  do_chunk <- function(start) {
    start <- start + 1L
    if (start > length(lines)) return()
    ## first empty line after start
    end <- empty[empty >= start][1]
    if (is.na(end)) end <- length(lines)
    lines[start:end] <<- sub("^## ", "", lines[start:end])
  }

  lapply(include, do_chunk)

  writeLines(lines, con = file)
}
后处理
postprocess <- function(file) {

  lines <- readLines(file)

  include <- grep("^## ---.*purl = TRUE.*$", lines)
  empty <- grep("^\\s*$", lines, perl = TRUE)

  do_chunk <- function(start) {
    start <- start + 1L
    if (start > length(lines)) return()
    ## first empty line after start
    end <- empty[empty >= start][1]
    if (is.na(end)) end <- length(lines)
    lines[start:end] <<- sub("^## ", "", lines[start:end])
  }

  lapply(include, do_chunk)

  writeLines(lines, con = file)
}