Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

latex - Putting line number for R code with knitr

I wonder if there is any function to put line numbers with knitr in .Rnw. I found this discussion and some documents (now removed from the web) but could not find the way to put line numbers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This solution uses the LaTeX listings package to create line numbers. I can only get them to work by accumulating across all code chunks, but I imagine there is a similar solution that will enumerate lines only within each chunk. Here's the .Rnw source:

documentclass{article}
usepackage{listings}
egin{document}

<<setup, echo=FALSE>>=
knit_hooks$set(source = function(x, options) {
    paste("\begin{lstlisting}[numbers=left, firstnumber=last]
", x, 
        "\end{lstlisting}
", sep = "")
})
@

<<a, results='hold'>>=
1:2
3:4
5:6
@

<<b>>=
"test1"
"test2"
"test3"
@

end{document}

The key parts of this are in the source hook, which is basically copied from here. The firstnumber=last tells listings to accumulate line numbers across listings. Without it, all lines are numbered 1 because knitr is putting each code line in its own listing.

And here's the result:

enter image description here

If you want each code block to start numbering from 1, add a hook to reset the counter:

knit_hooks$set(reset = function(before, options, envir){
if(before){
    return("\setcounter{lstnumber}{1}")
}
})

and then use reset=TRUE to activate the hook in each chunk you want:

<<a, results='hold', reset=TRUE>>=
1:2
3:4
@

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...