Search code examples
rknitrrnw

Read chunk from Rmd file to Rnw file


I want to read chunks in an RMD file from an RNW file, both of which are in different folders. I cannot make it work. It seems like it is not possible to read chunks from an RMD file. read_chunk() function seems to read only from an .R file. But in my case I cannot make it work as well.

Here are my three files (in different folders) and the output of my RNW file at the end. Any ideas why this is not working?

"..\Folder_R\trial_r.R"

## @knitr r_chunk_1
14 + 17
cat("SUCCESS THIS IS R CHUNK 1!!!")

## @knitr r_chunk_2
plot(cars)

"..\Folder_html\trial_html.RMD"

---
title: "Untitled"
output: html_document
---

```{r html_chunk_1}
## @knitr html_chunk_1
cat("SUCCESS THIS IS HTML CHUNK 1!!!")
```

```{r html_chunk_2, echo=FALSE}
## @knitr html_chunk_2
plot(cars)
```

"..\Folder_latex\trial_latex.RNW"

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

<<echo=FALSE>>=
library(knitr)

if (file.exists(file.path("..","Folder_html", "trial_html.Rmd")))
  cat("`trial_html` File Exists!!\n\n")

read_chunk(file.path("..","Folder_html", "trial_html.Rmd"))
@


<<latex_chunk_1, echo=FALSE>>=
cat("This is LATEX Chunk!!")
@

<<latex_chunk_2, ref.label='html_chunk_1', echo=FALSE>>=
@

<<latex_chunk_3, echo=FALSE>>=
<<html_chunk_1>>
@

<<html_chunk_1, echo=FALSE>>=
@

<<latex_chunk_4, echo=FALSE>>=
if (file.exists(file.path("..","Folder_R", "trial_r.R")))
  cat("`trial_r` File Exists!!\n\n")
read_chunk(file.path("..","Folder_R", "trial_r.R"))
@

<<latex_chunk_5, echo=FALSE>>=
<<r_chunk_1>>
@

<<r_chunk_2>>=
@

\end{document}

As a result the only thing I see in the PDF file is :

`trial_html` File Exists!!
This is LATEX Chunk!!
`trial_r` File Exists!!

I checked following sources THIS, THIS is somewhat what I want but did not help to solve my problem, and THIS is very helpful but I cannot make it work.

My warning message from the compilation is:

You can now run (pdf)latex on 'trial_latex.tex'
Warning messages:
1: In utils::Sweave("trial_latex.Rnw", encoding = "ISO8859-1") :
  reference to unknown chunk 'html_chunk_1'
2: In utils::Sweave("trial_latex.Rnw", encoding = "ISO8859-1") :
  reference to unknown chunk 'r_chunk_1'
Running pdflatex.exe on trial_latex.tex...completed

Solution

  • I think you were using Sweave instead of knitr. If you were using RStudio, be sure to change the option: