使用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)
}