I am using params
in Rmarkdown. However when using params and making sure everything works, I reconstruct params as a list in my global env and run the document chunk by chunk to make sure it is creating the correct report. I ran across an issue where the params in the yaml was overwriting my list in my global environment. if you run the first chunk without knitting it will createa the params list with the value being 6. then if you run the second chunk (ctrl + shift +enter) it will run the whole chunk. BUT it will overwrite the params list with the default value in the yaml. However when I run it line by line (ctrl + enter) this issue does not happen. What is happening when I run ctrl +shift +enter that is make the list being overwritten?
This also happens in .qmd
files.
---
title: "test"
author: "Michael"
output: html_document
params:
id: "4"
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE
)
params <- list(id = 6)
```
```{r}
library(dplyr)
mtcars %>%
filter(cyl == params$id)
```
You can get around that issue (in both rmd and qmd files) by only running params <- list(id = 6)
when you are in an interactive session. So this works for me:
---
title: "test"
author: "Michael"
output: html_document
params:
id: "4"
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE
)
if (interactive()) params <- list(id = 6)
```
```{r}
library(dplyr)
mtcars %>%
filter(cyl == params$id)
```
Since knitting is not interactive, creating the params object gets ignored.
Since chunk option also take code and evaluate it, you can even run a specific setup chunk for interactive sessions like this:
```{r setup, include=TRUE, eval=interactive()}
On a sidenote: I could not even knit the file without the condition, as I would run into this error:
Quitting from lines 10-16 (test.qmd)
Error in eval(expr, envir, enclos) :
cannot change value of locked binding for 'params'
A different option could be using eval=FALSE
(not runned when knitting) in your params chunk so you could knit it using the yaml
id, but if you want to use the created param you could run that line of code:
---
title: "test"
author: "Michael"
output: html_document
params:
id: "4"
---
```{r setup, include=TRUE, eval=FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE
)
params <- list(id = 6)
```
```{r}
library(dplyr)
mtcars %>%
filter(cyl == params$id)
```
Output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With