Read chunk from Rmd file to Rnw file - r

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

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

Related

Run R markdown (.Rmd) from inside other R script to produce HTML

As the example, if you create a new R markdown file and save it as 'test'. Can one then run or deploy this test.Rmd file from within a normal R script. The purpose being to generate the output in HTML, without having to open the .Rmd file.
I'm hoping to create one master file to do this for many markdown files in one go; which would save considerable time as you then don't have to open many markdown files and wait for each one to complete.
You are looking for rmarkdown::render().
Contents of "test.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
Contents of script.R
# provided test.Rmd is in the working directory
rmarkdown::render("test.Rmd")
A Way to Render Multiple Rmd
cwd_rmd_files <- list.files(pattern = ".Rmd$")
lapply(cwd_rmd_files, rmarkdown::render)
Thanks the-mad-statter, your answer was very helpful. The issue I faced, required me to prepare markdown dynamically. By adapting your code, that's easily possible:
Contents of "test_dyn.rmd"
---
title: "Untitled"
output: html_document
---
The chunk below adds formatted text, based on your inputs.
```{r text, echo=FALSE, results="asis"}
cat(text)
```
The chunk below uses your input in as code.
```{r results}
y
```
Contents of "script_dyn.r"
in_text <- c("**Test 1**", "*Test 2*")
in_y <- 1:2
lapply(1:2, function(x) {
text <- in_text[[x]]
y <- in_y[[x]]
rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
})
Like this you can create files with different text and different variables values in your code.

r - trying to run knitr chunk - Error: unexpected input in "<<"

this is my first question here so please forgive if it is unclear/messy.
I'm trying to reproduce the example in this page, reading chunks from an .R script and running them in an .Rmd markdown using knitr. The read_chunk() command seems to execute properly, but when I try to reference the chunks with the <<some_chunk>> notation R gives me: Error: unexpected input in "<<".
I have W10x64 and I'm using R v 3.5.1 with RStudio v1.1.456
This is the content of the .R script:
# This is our external R script called example.R
# We're adding two chunks variablesXY and plotXY
## #knitr variablesXY
x<-1:100
y<-x+rnorm(100)
head(data.frame(x,y))
## #knitr plotXY
plot(x,y)
And this is inside the .Rmd markdown (I got the error when I try to call <<variablesXY>>):
```{r}
library(knitr)
```
# read chunk (does not run code)
```{r echo=FALSE}
read_chunk('example.R')
```
# run the variablesXY chunk and use the variables it creates
```{r first}
<<variablesXY>>
head(data.frame(x,y))
```
# run the plotXY chunk and create the plot
```{r second}
<<plotXY>>
```

Display the knitr code chunk source in document

I'm trying to output the source of a knitr chunk onto a beamer slide.
For example, I would like the following code chunk to be displayed as is in the .Rnw:
<<code-chunk, echo=TRUE, tidy=TRUE>>=
#
I've attempted to recreate this behavior using:
<<out-first-code-chunk, echo=FALSE, comment=NA>>=
cat(paste("<<example-code-chunk, echo=TRUE, tidy=TRUE>>=","#",sep="\n"))
#
This code is legitimate since the cat command in R's console gives:
> cat('<<example-code-chunk, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
<<code-chunk, echo=TRUE, tidy=TRUE>>=
#
However, the resulting latex:
\begin{frame}
\frametitle{Code Chunk}
To incorporate R code into your knitr documents
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
<<example-code-chunk, echo=TRUE, tidy=TRUE>>=
#
\end{verbatim}
\end{kframe}
\end{knitrout}
Throws errors:
<<example-code-chunk, echo=TRUE, tidy=TRUE>>= # \end {verbatim} \end
\ETC. ! Paragraph ended before \#xverbatim was complete. <to be read
again> \par l.198 \end{frame} I suspect you've forgotten a `}',
causing me to apply this control sequence to too much text. How can we
recover? My plan is to forget the whole thing and hope for the best. !
LaTeX Error: \begin{verbatim} on input line 198 ended by
\end{beamer#framepau ses}. See the LaTeX manual or LaTeX Companion for
explanation. Type H <return> for immediate help. ... l.198 \end{frame}
Your command was ignored. Type I <command> <return> to replace it with
another command, or <return> to continue without it. ! LaTeX Error:
\begin{kframe} on input line 198 ended by \end{beamer#frameslide }.
Why is the latex environment thinking that verbatim was not closed? Is there a more appropriate way to display a code-chunk in its entirety?
This should do it...
1 line in the setup chunk, and 1 extra param in the chunk desired for output...
Console:
`install.packages(devtools)`
`devtools::install_github("thell/knitliteral")`
For .Rnw:
<<"knitr-setup", include=FALSE, cache=FALSE>>=
knitLiteral::kast_on()
#
<<"my_chunk", eval=FALSE, opts.label="literal-literal">>=
# Something that will not be output in the doc.
#
Output:
<<"my_chunk", eval=FALSE>>=
#
For .Rmd:
````{r knitr_setup, include=FALSE, cache=FALSE}
knitLiteral::kast_on()
````
````{r my_chunk, opts.label="literal-literal"}
# Something that will not be output in the doc.
````
Output:
````{r my_chunk}
````
** The use of 4 backticks keeps syntax highlighting as valid R (where used).
From this chunk and what you can see in the source of the example Literal Markdown doc and the rendered doc that there is no need to have a complex chunk.
The sweave example file is also available showing the same examples.

Could the \include{} command be used in a knitr .Rnw file?

Using \include{} usually works, unless there are code chunks in the file to be included:
\documentclass{article}
\begin{document}
% \include{test.tex}
\include{test.Rnw}
\end{document}
with test.tex or test.Rnw define e.g. by
<<echo=TRUE,eval=TRUE>>=
plot(cars)
#
won't display the cars plot. Is there some chance to find a way to bypass that trouble?
Thanks,
Julyan
You can include .Rnw file with child.
\documentclass{article}
\begin{document}
<<test, child='test.Rnw'>>=
#
\end{document}
were test.Rnw contains:
<<echo=TRUE,eval=TRUE>>=
plot(cars)
#

Is it possible to call external R script from R markdown (.Rmd) in RStudio?

It's fairly trivial to load external R scripts as per this R Sweave example:
<<external-code, cache=FALSE>>=
read_chunk('foo-bar.R')
#
Can the same be done for R Markdown?
Yes.
Put this at the top of your R Markdown file:
```{r setup, echo=FALSE}
opts_chunk$set(echo = FALSE, cache=FALSE)
read_chunk('../src/your_code.R')
```
Delimit your code with the following hints for knitr (just like #yihui does in the example):
## #knitr part1
plot(c(1,2,3),c(1,2,3))
## #knitr part2
plot(c(1,2,3),c(1,2,3))
In your R Markdown file, you can now have the snippets evaluated in-line:
Title
=====
Foo bar baz...
```{r part1}
```
More foo...
```{r part2}
```

Resources