Prevent chunk evaluation in R Notebook interactive - r

Using the chunk option eval=FALSE one can suppress chunk evaluation in an RMarkdown file or R Notebook when it is knit. Is there a way to make this apply during interactive running of the document in RStudio (i.e., making "run all chunks" skip certain chunks)?
I've got some chunks in the beginning of my analysis that take a while to run, which the later sections don't depend on. I want to be able to source the important parts of the code so I can continue writing the downstream stuff, without having to do it manually chunk-by-chunk so I can avoid the parts I don't need in my workspace for further writing.
I've set up the rmarkdown document with logical parameters meant to change which parts of the code need to get run - I meant these as control flags for when the code is actually finished and getting used, but I was hoping I could use those same parameters to exclude chunks from running in interactive mode (i.e., something like eval=params$run_part1).

Setting knitr::opts_chunk and knitr::opts_hooks only help you when knitting, not in interactive mode, so while I could be wrong I'm going to tentatively say you can't control that behavior with dynamic chunk options (yet).
As a workaround you could use interactive() and if blocks so that the code is only run when knitted. It would also mesh well with your logical parameters, despite the pain of having to be in a bracket block.
---
title: "R Notebook"
output:
html_document: default
html_notebook: default
---
```{r}
if (!interactive()) {
print("long running code")
}
```
```{r}
print(2)
```
```{r}
print(3)
```
Pressing "Run All Chunks Above":
Knitting:

Related

static image of targets workflow, programatically

I'm trying to embed a static image of a targets workflow in an rmarkdown document. I tried to do this by using tar_mermaid, defining a target that writes the workflow in mermaid format mm <- tar_mermaid(); writeLines(mm, "target_mermaid.js") but the help for tar_mermaid says
You can visualize the graph by copying
the text into a public online mermaid.js editor or a mermaid GitHub code chunk
I am looking for a programmatic way to either (1) embed the Javascript output in an (R)markdown file, or (2) render it (as SVG, PNG, whatever).
I thought as a shortcut that I could cut-and-paste into a markdown code chunk delimited by ```mermaid, or use cat(readLines("target_mermaid.js"), sep = "\n") in a chunk with results = "asis" but I guess that only works in Github markdown (I'm using Pandoc to render to HTML) ... ?
The visNetwork package has a visSave() function which can save to HTML (not quite what I wanted but better than what I've managed so far), and a visExport() function (which saves to PNG etc. but only by clicking in a web browser). Furthermore, targets wraps the visNetwork functions in a way that is (so far) hard for me to unravel (i.e., it doesn't return a visNetwork object, but automatically returns a widget ...)
For the time being I can go to https://mermaid.live, paste in the mermaid code, and export the PNG manually but I really want to do it programmatically (i.e. as part of my workflow, without manual steps involved).
I am not quite sure about the answer. But I have an idea. And I will delete if it is not adequate:
If you want execute mermaid code to get for example an html output then you could do this with quarto. I am not sure if this is possible with rmarkdown:
See https://quarto.org/docs/authoring/diagrams.htmlS
---
title: "Untitled"
format: html
editor: visual
---
## Quarto
Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see <https://quarto.org>.
## Running Code
```{mermaid}
flowchart LR
A[Hard edge] --> B(Round edge)
B --> C{Decision}
C --> D[Result one]
C --> E[Result two]
```
output:
#landau's suggestion to look here almost works, if I'm willing to use Quarto instead of Rmarkdown (GH Markdown is not an option). The cat() trick was the main thing I was missing. The .qmd file below gets most of the way there but has the following (cosmetic) issues:
I don't know how to suppress the tidyverse startup messages, because targets is running the visualization code in a separate R instance that the user has (AFAIK) little control of;
the default size of the graph is ugly.
Any further advice would be welcome ...
---
title: "targets/quarto/mermaid example"
---
```{r}
suppressPackageStartupMessages(library("tidyverse"))
library("targets")
```
```{r, results = "asis", echo = FALSE}
cat(c("```{mermaid}", tar_mermaid(), "```"), sep = "\n")
```
Beginning of document:
Zooming out:

Can I have run and knit give the same results with external code?

Since I have some fairly large code chunks (plantuml charts, sql), I'd prefer to keep those as external files. I see in the knitr manual I can do something like code=readLines(...) to bring in outside sources.
When using external code this way, I'm seeing a difference in behavior between running the chunk in RStudio with the green play button, and knitting the code.
With these two files:
main.R:
---
title: "test"
author: "Me"
date: "6/17/2020"
output: html_document
---
```{r setup, include=FALSE}
library(here)
library(xfun)
```
```{r, code=xfun::read_utf8(here::here('test.R'))}
print('world')
```
and test.R:
print('hello')
when I knit, hello is printed. When I run the code chunks using run in RStudio, or restart R and run all chunks, then the preview says world. The print('world') here is just to illustrate that the inline code is being ran; in my case, the inline code would be empty.
I see in the comments that "Knitr will replace the code in the chunk with the code in the code option", but does that mean that separate chunks are not run by knitr by another environment? Can I do something to have the external code be executed by both rather than one executing the inline code and the other the external code?

Conditional execution of code segments

I am working on a data set using both my laptop and a cloud facility. I want to compute some "computation-heavy" code chunks only when working on the cloud.
So far, I have chosen a not very elegant way to do so. I have added ##OPT## prefixes to segments which I want to execute only when in the cloud. I then simply remove these prefixes and run the script when in the cloud.
Now my question: is there a way that I can select in the beginning of the script once whether to execute these segments or not and then skip these segments if the argument is set to "false"? I have tried with if conditions but this is very cumbersome.
If you use an R notebook in RStudio, you can include the different code in different code chunks in the document. Code chunks are defined like:
```{r}
"hello world!"
```
Doing this allows you to quite easily run only the chunks that you want to run. Additionally, if you wish to run all of the chunks, you can do so.
Any given chunk possess an option called eval which dictates whether or not they should be run. This can take a value from an expression so you can essentially do something like:
```{r label}
is_cloud <- FALSE #or TRUE
```
```{r conditional, eval = is_cloud}
"hello world!"
```
and the chunk will be executed only if is_cloud is TRUE.
To further explain the comment of docendo discimus, just define a parameter at the beginning of your script:
execpart <- TRUE #and change to FALSE if you don't want to execute
Then wrap the whole part of your script which should only be executed situationally in:
if(execpart){
## your script
}
You could even define multiple parameters for different parts of your script at the beginning. That would give you the option to set up the execution of your script with a few quick changes.
Note that if looks for TRUE/FALSE, so you do not need to specify (execpart == TRUE) in your if-condition.
In RStudio R notebooks is is convenient to combine the nice suggestion in another answer with using "params" in the notebook header. E.g.:
---
title: params example
output: html_notebook
params:
in_cloud: yes
---
This one always runs:
```{r}
print("hello always")
```
This one only runs when in_cloud is TRUE:
```{r, eval=params$in_cloud}
print("hello, cloud")
```
Conditional blocks also work for other engines (like bash):
```{bash, eval=params$in_cloud}
echo "hello, cloud, from bash"
```

rmarkdown error "attempt to use zero-length variable name"

When i generate a new rmarkdown file (or open existing rmarkdown-files) and try to run a rmarkdown chunk, i get this error: "Error: attempt to use zero-length variable name".
I have Win10 and did a fresh install of R and Rstudio yesterday. What did i miss? Where does this error come from?
```{r cars}
summary(cars)
```
```{r cars}
Error: attempt to use zero-length variable name
Putting this as an answer for visibility: this happens if you try to run by selecting all in the Rmd and pressing enter like you would with a normal R script. RStudio tries to run this all as R code, including the markdown parts, leading to the errors you saw.
You can avoid this by running an individual chunk by clicking the green play button or by selecting one of the run options in the dropdown at the top of the Rmd editor.
For me the issue was that I had a missing backtick in the closing code block. In other words, it looked like the following (note that there are only two closing backticks, not three as there should be).
```{r}
# do some stuff
``
So the two backticks were being processed as part of the code block, which is legal code for supplying a variable name such as e.g.
`+`
But since no variable name was provided between the backticks, I was getting the "attempt to use zero-length variable name" error.
The problem could be due to the object being changed in the global environment in an earlier session and that session got saved in the global ennvironment. It is better to not save anything in the global environment, while ending the Rstudio session (or R console). One option would be to call the data(cars) again so that we get the original dataset
---
title: "Untitled"
output:
html_document: default
'html_document:': default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r cars}
data(cars)
summary(cars)
-output
One option to avoid these kind of surprises is to use the "Don't save" option while quitting the session
check the header's.. very top of the script / page..
---
title: "R Notebook" -->
author: "your_name_here" -->
date: "28/05/2022" -->
output: html_document --> 'notebook' returns 'zero-length' error..
---
from above, change...
output: html_notebook
...to...
output: html_document
I got the same message, my error was to have four backtick in one of the block codes
I had the same error. The problem was that comments within the code chunk had missing '#´s. The particular code chunk partially executed, showing the results and a syntax warning (but the markdown did not knit) What happened what that I used the keyboard short cut of 'CTRL+AlT+I" to insert a code chunk and it 'swallowed' the comments. A sneaky error to be sure.
I had the following code in my R Studio to suppress some warnings. What I wanted to do was hide all possible output but still evaluate the code, e.g., hide text output (results='hide'), hide warnings, hide messages
```{r message=FALSE, warning=FALSE, results='hide'}
When I got rid of those lines, I stopped getting the error as well.
Hope that helps.
I still get the same error, could you help? I am trying to copy the code for Iran from https://github.com/timchurches/blog/blob/master/_posts/2020-02-18-analysing-covid-19-2019-ncov-outbreak-data-with-r-part-1/analysing-covid-19-2019-ncov-outbreak-data-with-r-part-1.Rmd.
In my case this issue was caused by copying the sequence "''' {r}" into the R studio document. After manually re-entering this phrase, everything worked fine and I successfully generated a markdown file.
This approach involves selecting (highlighting) the R code only (summary(pressure)), not any of the backticks/fences from the code chunk. (If you see Error: attempt to use zero-length variable name it is because you have accidentally highlighted the backticks along with the R code........source: https://rstudio-conf-2020.github.io/r-for-excel/rstudio.html

Conditional `echo` (or eval or include) in rmarkdown chunks

I would like to create an Rmarkdown document (pdf or html) that has some chunks "executed" conditionally. The particular case I have in mind is that I might want a more verbose and documented version of the output for internal review by colleagues, and a shorter version for external consumers. I may not want or need to show data manipulation steps to a client, but just key graphs and tables. I also do not want to make two separate documents or have to manually indicate what to show or not.
Is there a way to set a switch at the beginning of the Rmd that indicates, e.g., verbose=T that will run all chunks or verbose=F that toggles echo=F (or include=F)?
Thank you.
knitr options can be stated as R expressions. Per the "output" documentation on the knitr webpage:
Note all options in knitr can take values from R expressions, which brings the feature of conditional evaluation introduced in the main manual. In short, eval=dothis means the real value of eval is taken from a variable named dothis in the global environment; by manipulating this variable, we can turn on/off the evaluation of a batch of chunks.
In other words if you write some chunks like:
```{r label}
doNextChunk <- as.logical(rbinom(1,1,.5))
```
```{r conditional, eval = doNextChunk}
"hello world!"
```
opts_chunk$set() is what you are after. Anything "set" will be the default for subsequent chunks (unless overwritten on a chunk-by-chunk basis)
```{r setup}
library(knitr)
opts_chunk$set(eval = TRUE, include= TRUE)
````
You can then alter as you see fit.

Resources