When starting knitting to exit .Rmd pieces are invalid

Problem

When trying knit.Rmd, containing the lines read_chunkfrom the purlscripts, to the parent .Rmd, the pieces are not complete and form only blocks of code. I want to be able knitto output the file normally.

The code

main.Rmd

---
output: html_document
---

```{r, include=FALSE}
knitr::read_chunk("script_chunk.R")
```

### Print sessionInfo()

```{r, ref.label='script_chunk', eval=FALSE}
``` 

script_chunk.R

# ---- script_chunk
sessionInfo()

Knitting

When I process this with knit("main.Rmd", "output.Rmd"), the following file is created:

---
output: html_document
---



### Print sessionInfo()


```r
sessionInfo()
```

However, the desired output for the block:

```{r script_chunk}
sessionInfo()
```

When I knitoutput.Rmd at the moment, I get only an unappraised code block because the piece does not have curly braces (and preferably the name of the piece).

enter image description here

Bypass

I can use readLinesto achieve what I need, for example:

```{r, results='asis', collapse=TRUE, echo=FALSE}
cat("```{r script_chunk}\n")
cat(paste(readLines("script_chunk.R"), "\n", collapse = ""))
cat("```\n")
```

Is there a more elegant way to do this?

+4
2

:

# main.Rmd
---
output: html_document
---

### Print sessionInfo()

```{r, results="asis", echo = FALSE}
chunk_lines <- knitr::spin(text = readLines("script_chunk.R"), knit = FALSE)
cat(chunk_lines, sep = "\n")
```

, , knitr, Markdown. knitr : LaTeX, Sweave, HTML, Markdown Jekyll. .Rmd, Markdown, R Markdown.

, , , . main.Rmd.

+6

, , knit_child:

  • main.Rmd

    ---
    output: html_document
    ---
    
    ```{r, include=FALSE}
    out <- knitr::knit_child("script_chunk.Rmd")
    ```
    
    ### Print sessionInfo()
    ```{r, ref.label='script_chunk'}
    paste(out, collapse = "\n")
    ```
    
  • script_chunk.Rmd

    ```{r script_chunk}
    # ---- script_chunk
    sessionInfo()
    ```
    

:

---
output: html_document
---

### Print sessionInfo()

```r
# ---- script_chunk
sessionInfo()
```

```
## R version 3.3.3 (2017-03-06)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 16299)
## ... blah blah blah ...
```

:

  • out - ;
  • ( "" ) , out knit_child
+3

Source: https://habr.com/ru/post/1691148/


All Articles