用knitr为R代码输入行号 [英] Putting line number for R code with knitr

查看:18
本文介绍了用knitr为R代码输入行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道有没有什么函数可以把line numbersknitr放在.Rnw中.我找到了 这个讨论 和一些文档(现已从网上删除)但找不到放置行号的方式.

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.

推荐答案

此解决方案使用 LaTeX listings 包来创建行号.我只能通过累积所有代码块来让它们工作,但我想有一个类似的解决方案可以仅在每个块中枚举行.这是 .Rnw 源代码:

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}

这里的关键部分在source hook中,基本上是从这里复制过来的.firstnumber=last 告诉列表在列表中累积行号.没有它,所有行都编号为 1,因为 knitr 将每个代码行放在自己的列表中.

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.

结果如下:

如果你想让每个代码块从 1 开始编号,添加一个钩子来重置计数器:

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}")
}
})

然后使用 reset=TRUE 来激活你想要的每个块中的钩子:

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

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

这篇关于用knitr为R代码输入行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆