Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

knitr

I'm using knitr to create a markdown file from Rmd and I have the following option set at the top of my .Rmd script to hide all results and plots:

```{r, echo=FALSE}
opts_chunk$set(results="hide", fig.show="hide")
```

When I hit the Knit HTML button in RStudio, this works - I get output without the results and figures. But if I run from the command line:

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

It appears the opts_chunk$set() line isn't read, and I get results and plots in my .md output. I've worked around the problem by specifying these options in the Rscript command:

Rscript -e 'library(knitr); opts_chunk$set(results="hide", fig.show="hide"); knit("myfile.Rmd")'

But I'd rather keep all the options read from the file I'm using rather than specified at the command line. How do I get the options read in the .Rmd file when kniting with Rscript at the command line?

Thanks.

like image 357
Stephen Turner Avatar asked Mar 27 '14 17:03

Stephen Turner


People also ask

How do you use the knitr in R studio?

If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.

What is the function of knitr in creating markdown document?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.


1 Answers

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().

like image 188
Ben Bolker Avatar answered Sep 29 '22 06:09

Ben Bolker