LyX

Using knitr with LyX

2011-12-06

Since LyX 2.0.3, knitr can be used in LyX via a module named Rnw (knitr). See knitr.lyx for a simple example (pdf output). Just add the module to your document and install knitr in R; then you are done.

knitr module in LyX

An important note to all LyX users: a big trouble with LyX+Sweave is that we have got too many instructions in the past on how to configure LyX in order to work with Sweave. Many tutorials are becoming misleading and confusing (e.g. you no longer need to take care of noweb.sty). The only up-to-date source is the official LyX manual for Sweave.

Ubuntu users

To install LyX, you can either check out the source code and compile it by yourself:

./authgen.sh
./configure
make
make install

or use the PPA (much easier):

sudo add-apt-repository ppa:lyx-devel/release
sudo apt-get update
sudo apt-get install lyx

The one in the official repository is often lagging behind, and this PPA is up-to-date.

Other systems

If you use Windows or Mac OS, you can download LyX from http://www.lyx.org.

The most frequently seen trouble for Windows users is that R is not in PATH by default; see the manual above or the Stack Overflow post for the solution.

Other languages

If you are under Windows and using multibyte characters, you need at least LyX 2.0.6 and knitr 1.1. If your LyX version is lower than 2.0.6, you are likely to run into problems due to the file encoding.

Other examples

There are a couple of LyX examples under the examples directory of the package repository. Remember to check out the bib files as well if there are any.

Below is a short video of using knitr in LyX (no audio at the moment but I plan to make a full tutorial in the future):

Using knitr in LyX from Yihui Xie on Vimeo.

Some known issues

You should not let LyX mark foreign languages, otherwise it may ruin R code chunks; see #255 for details. Below are my language preferences in LyX:

Do not mark foreign languages

If your R code has output that contains single quotes, you may run into an error like:

! Undefined control sequence.
<argument> ^^M'
               ^^M
l.8 \end{verbatim}

To fix it, you need to update knitr to at least version 1.2.

For Mac OS X users, your OS has a weird bug that makes R fail to set up the locale when started from LyX. As a result, R cannot process multi-byte characters. You have to tell your locale info to R manually, e.g. in ~/.Rprofile:

cat('
Sys.setlocale(, "en_US.UTF-8")
', file = '~/.Rprofile', append = TRUE)

Here en_US.UTF-8 is just one possible locale. Your OS might be using other languages. To check what is the real locale, run Sys.getlocale() in a normal R session (e.g. start R from the terminal).