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

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

Related

Is it possible to create a self-rendering Rmarkdown document?

For typical R scripts the shebang syntax can be used to run the code within. With a file file.R
#!/usr/bin/env Rscript
<some R code here>
Running ./file.R will execute the code.
But can somehow the same be done with R-markdown? So that with a file named file.Rmd:
#!/usr/bin/env <some command>
<some markdown>
<some R code here>
<some markdown again>
Running ./file.Rmd would produce file.md?
You can treat an Rmd file as an Rscript. For instance, assume that your Rmd file looks like this
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
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)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
You can then prepend the following code to that Rmd file
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
The trick here is q("no"). This line terminates the R session, and, thus, whatever written after it will be ignored. Such an effect also means high flexibility for coding because you can write almost any valid R code before that q("no"). The code above simply creates another temporary Rmd file with the same content as what is after q("no"). Then, we rmarkdown::render that temporary file and dump the output to the current directory.
The complete Rmd file looks like this
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
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)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Disclaimer: I do not know much about Linux, nor do I have a Linux machine with R installed available to test my answer. Let me know if this does not work properly. If this inspires someone to write a better answer, I'll happily delete this one.
Let me approach this backwards:
To knit a document, we need to call rmarkdown::render().
To run this command from a command line, we can use RScript -e "rmarkdown::render('document.Rmd')", see e.g. here.
Probably you do not want to hardcode the path to Rscript but use a shebang like #!/usr/bin/env Rscript instead.
The problem with this approach is that it does not allow to pass arguments to Rscript.
I therefore propose to use a "wrapper" in the shebang that is responsible for calling Rscript.
With the name of the RMD file as argument, the required R code becomes rmarkdown::render(commandArgs(trailingOnly=TRUE)[1]).
Step by step:
Create the wraper (in any directory that is in your $PATH) and make it executable:
touch KnitWrapper.sh
chmod +x KnitWrapper.sh
Write the following to KnitWrapper.sh:
#!/usr/bin/env bash
Rscript -e "rmarkdown::render(commandArgs(trailingOnly=TRUE)[1])" $1
Make sure Rscript is in your $PATH. If you update R, update your $PATH accordingly.
In your RMD file, add the shebang #!/usr/bin/env KnitWrapper.sh.
Make your RMD file executable and run it:
chmod +x yourDocument.Rmd
./yourDocument.Rmd
Unfortunately, the above is largely untested. Let me know if it does not work, so I can either fix or delete this answer.

R notebook: rerunning chunks in different parts of code

Is there a way to rerun chunks in R notebook?
In knitr it is possible to rerun chunks simply by referencing their name. E.g. like this below, only the second chunk would output the result (source https://campus.datacamp.com/courses/reporting-with-r-markdown/chapter-two-embedding-code?ex=7).
```{r simple_sum, results = 'hide'}
2 + 2
```
```{r ref.label='simple_sum', echo = FALSE}
```
Is there a simple way to do the same thing in the R notebook environment?

Prevent Rmd code chunk from running by using variable when in interactive mode

When I knit this example .Rmd, the second chunk---as expected---does not evaluate but if I run all chunks interactively, the second chunk executes. What's the cleanest way to accomplish the equivalent of eval=FALSE for interactively running all chunks?
```{r}
RUN <- FALSE
```
```{r eval=RUN}
print("Code ran!")
```

Can't generate plotly interactive plots in Rmarkdown report

I have an Rmarkdown document with a plot made with plotly and would like to generate an html file. It works when I click on Knit to HTML in Rstudio, but not when I run the following on the command line:
Rscript -e "require(knitr)" -e "require(markdown)" -e "knit('Untitled.Rmd', out='report.md')" -e "markdownToHTML('report.md', 'report.html')"
After this, I have a report.html file which contains the plot generated with plotly, but it is not interactive.
Does anyone know how to make it interactive with the command line?
Thanks
This is the code, btw:
---
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)
```
## Including Plots
You can also embed plots, for example:
```{r pressure_ggplot, echo=FALSE}
library(ggplot2)
library(plotly)
ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
```{r pressure_plotly, echo=FALSE}
g<-ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
ggplotly(g)
```
```{r}
sessionInfo()
```
Try:
Rscript -e "library(knitr); library(rmarkdown); rmarkdown::render('untitled.Rmd', output_file='report.html')"
Reasoning: knit seems to default to markdown output, and doesn't retain HTMLwidgets in the rendered markdown. Thus, when converting, you end up with missing files (you can see these errors if you remove echo=FALSE from the code block openings.
rmarkdown::render([...]) renders cleanly to HTML, avoiding the issues mentioned above. If you wish to specify the output format, you can do so using the output_format argument.

sourcing and displaying R source code in R Markdown without executing

I am writing a book in R Markdown. I saved a lot of code in separate .R files. For didactical purpose I need to show the whole file's contents without actually running it.
e.g., I would like that
r my_r_chunk
source("./code/mycodefile.R")
```
would be rendered displaying the whole content of mycodefile.R without actually executing it.
Check out ?knitr::read_chunk
First, assign a label to the script using the syntax ## ---- your_label ---- by placing it in the first line of the script which is called foo.R
foo.r
## ---- your_label ----
print("Hello World")
1:10
After assigning the script a label, you can then read_chunk the script in an uncached chunk. Finally you reference the contents in a subsequent (cached) chunk using the eval = FALSE chunk option.
your_Rmd_file.Rmd
---
output: pdf_document
---
```{r cache=FALSE, echo = FALSE}
library(knitr)
read_chunk('foo.R')
```
```{r your_label, cache = TRUE, eval=FALSE}
```

Resources