在我看来,knitr::purl
不处理 block 引用。参见例如
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
输出中的 block ,我指定了 purl = TRUE
,例如
```{r label, eval = FALSE, purl = TRUE}
server <- function(input, output, session) {
rvs <- reactiveValues(data = NULL)
# ...
}
```
然后以通常的方式引用它们,但使用 purl = FALSE
例如
```{r ref.label = label, purl = FALSE, echo = FALSE}
```
然后使用此后处理函数取消注释具有 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)
}
关于r - 使用 knit::purl 进行 block 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41038256/