用Knitr放置R代码的行号 [英] Putting line number for R code with knitr

查看:140
本文介绍了用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 列表程序包创建行号.我只能通过累积所有代码块来使它们工作,但是我想象有一个类似的解决方案,它将仅枚举每个块中的行.这是.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}
\begin{document}

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

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

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

\end{document}

其中的关键部分位于源代码钩子中,基本上从此处复制 . 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天全站免登陆