2
votes

I've been reading all the documentation and examples I can find for Knitr's output hooks for editing the output of the document.

I'm using Knitr to process a .Rmd file, which looks like this:

[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) 
```

If I run

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

on the file, it renders (correctly) like this:

[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)

```

However, if I do anything to set the knit_hook "document" (which goes through the full document after it's parsed), the line breaks and code fences (```) in my code are deleted:

# 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)

Result:

[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)

I've seen several examples, including one from Yihui here, that lead me to think that setting the document hook and just having it give back x shouldn't do anything different than its default. What am I missing here?

Eventually, I'd like to set the document hook to use gsub() to replace the shortcode in the document with other code. But this issue with line breaks and code fences is confusing me in the meantime.

I'd be grateful for any advice on how to retain those line breaks and code fences when changing the document hook!

1

1 Answers

3
votes

You should set up the hook function inside the Rmd file. If you do it before knit(), you must call render_markdown() first.