Learn R Programming

⚠️There's a newer version (1.48) of this package.Take me there.

knitr

The R package knitr is a general-purpose literate programming engine, with lightweight API's designed to give users full control of the output without heavy coding work. It combines many features into one package with slight tweaks motivated from my everyday use of Sweave. See the package homepage for details and examples. See FAQ's for a list of frequently asked questions (including where to ask questions).

Installation

You can install the stable version on CRAN:

install.packages('knitr')

You can also install the development version from XRAN, which provides daily build of knitr:

# update all existing packages first
update.packages(ask = FALSE, repos = 'https://cran.r-project.org')
install.packages('knitr', repos = c('https://xran.yihui.org', 'https://cran.r-project.org'))

Note that if you want to build the source package via R CMD INSTALL without a previously installed version of knitr, you must either pre-install knitr from CRAN, or run R CMD INSTALL on this source repo, otherwise R CMD build will fail (which is probably a bug of base R).

Motivation

While Sweave and related add-on packages like cacheSweave and pgfSweave are fairly good engines for literate programming in R, I often feel my hands are tied. For example:

  • I stared at the source code of Sweave and wished for hundreds of times, if only I could easily insert [width=.8\textwidth] between \includegraphics and {my-plot.pdf}. (The official way in Sweave is \setkeys{Gin} but it is setting a global width, which is unrealistic since we often have to set widths individually; yes, you can use \setkeys{Gin} for many times, but why not just provide an option for each chunk?)
  • I wished for many times, if only I could use graphics devices other than PDF and postscript; now the dream has come true in the official R, but what I was hoping for was an option as simple as dev = 'png' or dev = 'CairoJPEG'.
  • I wished multiple plots in a code chunk could be recorded instead of only the last one.
  • I wished there was a way to round the numbers in \Sexpr{} other than writing expressions like \Sexpr{round(x, 3)} for each single \Sexpr{}
  • I wished I did not have to print() plots from. ggplot2 and a simple qplot(x, y) would just give me a plot in Sweave.
  • I wished users would never need instructions on Sweave.sty or run into troubles due to the fact that LaTeX cannot find Sweave.sty.
  • I wished cacheSweave could print the results of a code chunk even if it was cached.
  • I wished brew could support graphics.
  • I wished R2HTML could support R code syntax highlighting.
  • ...

The package knitr was designed to give the user access to every part of the process of dealing with a literate programming document, so there is no need to hack at any core components if you want more freedom. I have gone through the source code of pgfSweave and cacheSweave for a couple of times and I often feel uncomfortable with the large amount of code copied from official R, especially when R has a new version released (I will begin to worry if the add-on packages are still up-to-date with the official Sweave).

Usage

library(knitr)
?knit
knit(input)

If options are not explicitly specified, knitr will try to guess reasonable default settings. A few manuals are available such as the main manual, and the graphics manual. For a more organized reference, see the knitr book.

License

This package is free and open source software, licensed under GPL.

Copy Link

Version

Install

install.packages('knitr')

Monthly Downloads

1,175,558

Version

1.29

License

GPL

Maintainer

Last Published

June 23rd, 2020

Functions in knitr (1.29)

fig_chunk

Obtain the figure filenames for a chunk
include_graphics

Embed external images in knitr documents
knit

Knit a document
knit_exit

Exit knitting early
imgur_upload

Upload an image to imgur.com
kable

Create tables in LaTeX, HTML, Markdown and reStructuredText
knit_engines

Engines of other languages
knit2pandoc

Convert various input files to various output files using knit() and Pandoc
knit_params_yaml

Extract knit parameters from YAML text
knit2html

Convert markdown to HTML using knit() and markdownToHTML()
dep_prev

Make later chunks depend on previous chunks
render_html

Set output hooks for different output formats
is_latex_output

Check if the current output type is LaTeX or HTML
image_uri

Encode an image file to a data URI
hook_plot_html

Default plot hooks for different output formats
knit_meta

Metadata about objects to be printed
knit2pdf

Convert Rnw or Rrst files to PDF
knit_params

Extract knit parameters from a document
knit2wp

Knit an R Markdown document and post it to WordPress
opts_knit

Options for the knitr package
read_chunk

Read chunks from an external script
set_alias

Set aliases for chunk options
opts_template

Template for creating reusable chunk options
fig_path

Path for figure files
asis_output

Mark an R object with a special class
set_header

Set the header information
write_bib

Generate BibTeX bibliography databases for R packages
spin_child

Spin a child R script
read_rforge

Read source code from R-Forge
stitch

Automatically create a report based on an R script and a template
knit_child

Knit a child document
hook_ffmpeg_html

Hooks to create animations in HTML output
knit_code

The code manager to manage code in all chunks
knit_expand

A simple macro preprocessor for templating purposes
hook_movecode

Some potentially useful document hooks
engine_output

An output wrapper for language engine output
knit_filter

Spell check filter for source documents
knit_patterns

Patterns to match and extract R code in a document
include_url

Embed a URL as an HTML iframe or a screenshot in knitr documents
inline_expr

Wrap code using the inline R expression syntax
knit_global

The global environment in which code chunks are evaluated
load_cache

Load the cache database of a code chunk
knitr-package

A general-purpose tool for dynamic report generation in R
raw_block

Mark character strings as raw blocks in R Markdown
knit_hooks

Hooks for R code chunks, inline R code and output
knit_print

A custom printing function
knit_watch

Watch an input file continuously and knit it when it is updated
knit_theme

Syntax highlighting themes
plot_crop

Crop a plot (remove the edges) using PDFCrop or ImageMagick
extract_raw_output

Mark character strings as raw output that should not be converted
rand_seed

An unevaluated expression to return .Random.seed if exists
rst2pdf

A wrapper for rst2pdf
rocco

Knit R Markdown using the classic Docco style
opts_hooks

Hooks for code chunk options
set_parent

Specify the parent document of child documents
spin

Spin goat's hair into wool
opts_chunk

Default and current chunk options
pandoc

A Pandoc wrapper to convert documents to other formats
pat_rnw

Set regular expressions to read input documents
vignette_engines

Package vignette engines
wrap_rmd

Wrap long lines in Rmd files
knit_rd

Knit package documentation
current_input

Query the current input filename
all_labels

Get all chunk labels in a document
clean_cache

Clean cache files that are probably no longer needed
dep_auto

Build automatic dependencies among chunks
combine_words

Combine multiple words into a single string
Sweave2knitr

Convert Sweave to knitr documents
all_patterns

All built-in patterns
hook_pdfcrop

Built-in chunk hooks to extend knitr
cache_engines

Cache engines of other languages