尝试设置 Knitr 'document' 输出挂钩导致代码块换行符丢失

Trying to set Knitr 'document' output hook results in code chunk line breaks being lost

我一直在阅读我能找到的关于 Knitr output hooks 的所有文档和示例,以编辑文档的输出。

我正在使用 Knitr 处理一个 .Rmd 文件,它看起来像这样:

[SOME_SHORTCODE_TO_BE_REPLACED] (I eventually want this to be replaced by Knitr when it parses the document)

```{r echo=TRUE, eval=FALSE} 

data1 <- rnorm(10, mean = 0, sd = 10)

data2 <- rnorm(10, mean = 2, sd = 2)

model <- lm(data1 ~ data2)

summary(model) 
```

如果我运行

opts_chunk$set(tidy = FALSE)
knit(filename, output = outputFilename.markdown)

在文件中,它(正确)呈现如下:

[SOME_SHORTCODE_TO_BE_REPLACED] (I eventually want this to be replaced by Knitr when it parses the document)

```r

data1 <- rnorm(10, mean = 0, sd = 10)

data2 <- rnorm(10, mean = 2, sd = 2)

model <- lm(data1 ~ data2)

summary(model)

```

但是, 如果我对 设置 knit_hook "document"解析后的文档),删除了我代码中的换行符和代码围栏(```):

# As I understand, this *should* be identical to Knitr's default for the document hook, which is to just do:
# knit_hook$set(document = identity)

knit_hooks$set(document = function(x) {
    x
})
# (Then re-knit the file using the commands above)

结果:

[SOME_SHORTCODE_TO_BE_REPLACED] (I eventually want this to be replaced by Knitr when it parses the document)

data1 <- rnorm(10, mean = 0, sd = 10)data2 <- rnorm(10, mean = 2, sd = 2)model <- lm(data1 ~ data2)summary(model)

我看过几个例子,包括来自易汇 here 的一个例子,这让我认为设置文档挂钩并让它返回 x 不应该做任何不同的事情它的默认值。我在这里错过了什么?

最终,我想将文档挂钩设置为使用 gsub() 将文档中的短代码替换为其他代码。但与此同时,换行符和代码围栏的问题让我感到困惑。

如有任何关于如何在更改文档挂钩时保留这些换行符和代码栅栏的建议,我将不胜感激!

您应该在 Rmd 文件中设置挂钩函数。如果在 knit() 之前进行,则必须先调用 render_markdown()