Creating Notebooks from R Scripts in the RStudio IDE


Creating Notebooks from R Scripts


R Markdown provides an easy way to generate reports that include analysis, code, and results. However, if your code is in an R script rather than an R Markdown document you can still generate a report using the Compile Notebook command in the RStudio IDE:

Compiling a notebook for an R script automatically generates an R Markdown document, executes it, and then writes the results as a standalone HTML. pdf, or MS Word file. You'll find the Compile Notebook command for R scripts both on the File menu as well as on the source editor toolbar.

A Simple Example

For example, compiling the following R script to an HTML notebook:

Results in a web page that looks like this:

Any images included in the HTML file are embedded, so the document can be easily distributed as standalone file.

Notebook Output Types

When you compile a notebook, you can choose from the three output types described below.


The default notebook output type is shown above. This type includes all R code in a single R Markdown code block and modifies two of the default knitr options:

  1. Disables code reformatting (so your code appears exactly as it did in the R source file).
  2. Disables prepending of ## to output blocks. 

knitr spin

If you have knitr version 0.6 or higher, you can also choose to create a notebook by calling the knitr::spin function.

The spin function takes a specially formatted R script and produces an R Markdown document. Roxygen style comments (i.e. lines starting with #') are automatically turned into text and lines starting with #+ are parsed as chunk options. The following is an example of an R script formatted for spinning: knitr spin example.

You can find more details on these functions in the documentation for the knitr package as well as on the web at