Knitr: Opts_Chunk$Set() Not Working in Rscript Command

Knitr: opts_chunk$set() not working in Rscript command

I think you need to add

library("knitr")

to the chunk (you might want to set message=FALSE in the chunk options for that chunk).

The problem is that when you do

Rscript -e 'knitr::knit("myfile.Rmd")'

you're not actually attaching the knitr package, which means it isn't in the search path for functions, which means that R can't find the opts_chunk object.

  • Using knitr::opts_chunk might work too ...
  • as you suggested, so does Rscript -e 'library("knitr"); knit("myfile.Rmd")'

When you click the button in RStudio, RStudio automatically loads knitr in the environment in which it runs knit().

knitr::opts_chunk$set(message=FALSE) does not work

The changes made with knitr::opts_chunk$set will be activated starting th next chunk. See my example above. So it is recommended to setup your setting in the first chunk of your RMD file and then calculate/manipulate ... your data. See the official documentation here under Details.

```{r}
library(tidyverse)
knitr::opts_chunk$set(message=FALSE)
strMessage <- if_else(knitr::opts_chunk$get("message"),"TRUE","FALSE")
message(c("message is set to ",strMessage))
```

```{r}
strMessage <- if_else(knitr::opts_chunk$get("message"),"TRUE","FALSE")
message(c("message is set to ",strMessage))
```

Setting work directory in knitr using opts_chunk$set(root.dir = ...) doesn't work

It is knitr::opts_knit instead of knitr::opts_chunk.

Is there a global command line knit option as eval=FALSE for all chunks?

You do not need to edit the .Rmd file. You can just run

knitr::opts_chunk$set(eval = FALSE)

before running knitr::knit(); knitr will respect the global chunk options you set before calling knitr::knit().

Rmarkdown does not follow same paths as R script and console commands

Try something that looks like this as I am not sure of the nature of your `R Markdown.

test <- readRDS(here::here("data/test_data.rds"))

The bottom line is to use the here function from the here package.



Related Topics



Leave a reply



Submit