knitr templates and child documents in a loop

2019-03-25 19:41发布

问题:

Before Christmas I previously asked single style sheet across multiple knitr documents. I now know that the key search term I was missing is "child document".

I have created a minimal markdown example but I am getting headers in the created document that are part of the knitting process. I am using RStudio to process it. I have seen many similar questions, but none of the answers work. I have tried various combinations of the chunk parameters and so far to no avail.

Question: How do I get rid of the header from the final knitted document?

# Master document

```{r master1, comment='', echo=FALSE, message=FALSE, warning=FALSE, results="asis", fig.width= 4., fig.height= 4, fig.cap= ""}
out = NULL
for (i in 1:3) {
  # lets create three different uniform data sets.
  v1 <- sort(rnorm(2))
  uvec <- runif(10, v1[[1]], v1[[2]])
  # now we want to 
  out <- c(out, knit_child('child.Rmd'))
}
cat(paste(out, collapse = '\n'))
```

The child document contains:

## child document `r i`

Here is a summary of the dataset:
```{r echo=FALSE}
summary(uvec)
```

Unfortunately I also get an annoying header ....

|
| | 0% |
|…………………. | 33% inline R code fragments

|
|……………………………………. | 67% label: unnamed-chunk-1

|
|………………………………………………………..| 100% ordinary text without R code

|
| | 0% |
|…………………. | 33% inline R code fragments

|
|……………………………………. | 67% label: unnamed-chunk-2

|
|………………………………………………………..| 100% ordinary text without R code

|
| | 0% |
|…………………. | 33% inline R code fragments

|
|……………………………………. | 67% label: unnamed-chunk-3

|
|………………………………………………………..| 100% ordinary text without R code

回答1:

The answer given by Sean didn't work for me. The code that worked for me was:

# Master document

```{r echo=FALSE, include=FALSE}
library(knitr)

out = NULL
for (i in 1:3) {
  # lets create three different uniform data sets.
  v1 <- sort(rnorm(2))
  uvec <- runif(10, v1[[1]], v1[[2]])
  out <- c(out, knit_child('child.Rmd'))
}
```

```{r, echo=FALSE, results="asis"}
cat(paste(out, collapse = '\n'))
```


回答2:

One answer is to use knit_expand() instead of knit_child() and to knit(, quiet=TRUE) later - here is a revised master document.

# Master document
```{r master1, comment='', echo=FALSE, message=FALSE, warning=FALSE, results="asis", fig.width= 4., fig.height= 4, fig.cap= ""}
out = NULL
for (i in 1:3) {
  # lets create three different uniform data sets.
  v1 <- sort(rnorm(2))
  uvec <- runif(10, v1[[1]], v1[[2]])
  out <- c(out, knit_expand('child.Rmd'))
}
cat(knit(text=unlist(paste(out, collapse = '\n')), quiet=TRUE))
```


回答3:

I ran into the same problem with Latex instead of markdown and the solution for me was to use the \Sexpr instead of a code block

In addition, knit_child('child.file', quiet=TRUE) works as well



标签: r markdown knitr