在我看来,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运行的代码吗?
发布于 2016-12-11 21:31:52
以下是我作为变通办法所做的工作。对于我不想运行但想要包含在.html和.R输出中的块,我指定了purl = TRUE,例如
```{r label, eval = FALSE, purl = TRUE}server <- function(输入、输出、会话){
rvs <- reactiveValues(data =空)
..。
}
然后用通常的方式来指代它们,但用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)
}https://stackoverflow.com/questions/41038256
复制相似问题