Search code examples
rknitrreportingsweave

Adding line numbers for R code chunks with knitr with Lyx


I am using Lyx with the R knitr package and am having a hard time placing line numbers into my code chunks in R. I want every line of my code to have a number, not just output lines as I've seen in posts.

So, for example, I'd like to see my code that looks like this:

x <- 1:10
y <- x^2

Rendered like this is my final PDF document

1  x <- 1:10
2  y <- x^2

I saw a similar discussion here, but I'd like to accomplish this within LyX if possible.


Solution

  • After some research I discovered a workable solution, but I'd still be interested in other solutions too.

    When using knitr with Lyx or Latex, I've found it helpful to add the lineno package to the document pre-amble and then to enclose the chunk with the \internallinenumbers \resetlinenumber[13].

    Here's a minimal example:

    \usepackage{lineno}
    

    then in the body text, add the following before the code chunk:

    {\internallinenumbers \resetlinenumber[13]
    

    and then this after the code chunk:

    }
    

    With LyX (what I use for rapid LaTeX generation), I simply go to the document menu, then Settings->LaTeX Preamble and I add \usepackage{lineno}, click Apply, OK, and then Close. Then in the main document before my code chunk, I insert LaTeX source by clicking the "TEX" button menu button or by pressing "Ctrl+L" on the keyboard. Then I paste in {\internallinenumbers \resetlinenumber[13]. Finally, I place the cursor immediately after the code chunk and do the same thing. only I close the line numbering with a curly brace: }.

    Here is a minimal example, when the code is in place is pasted below:

    \documentclass[english]{article}
    \usepackage{lineno}
    \begin{document}
    First line in main document before code chunk.
    
    {\internallinenumbers \resetlinenumber[13]
    
    <<CodeBlock1, highlight=TRUE, eval=FALSE, size="small">>=
    x<-rnorm(10)
    mean(x)
    @
    }
    \end{document}