Knitr
原 文:Knitr
译 者:Xovee
翻译时间:2024年3月23日
Knitr是一个基于R语言的动态报告生成引擎。本文介绍如何在LaTeX文档中添加R语言代码来生成动态内容。
在一个标准的LaTeX发行版中,你首先得在操作系统中安装好R,然后使用一些特殊的命令来编译它。在Overleaf中,你可以免去这些烦恼。
介绍
包含R语言代码的文档必须以.Rtex
或者.Rnw
后缀保存,否则代码不会执行。让我们看一个例子:
\documentclass{article}
\begin{document}
You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:
<<>>=
# Create a sequence of numbers
X = 2:10
# Display basic statistical measures
summary(X)
@
\end{document}
如图所示,符号<<>>=
以及@
中内容是R语言代码。代码的输入格式类似于一个列表。你还可以使用一些额外的参数来自定义动态输出的内容。让我们看下一个例子。
代码块
一个代码块(如上例中的代码)一般被称为Chunk。你可以对knitr chunk设置一些额外的参数:
\documentclass{article}
\begin{document}
You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:
<<echo=FALSE, cache=TRUE>>=
# Create a sequence of numbers
X = 2:10
# Display basic statistical measures
summary(X)
@
\end{document}
这些额外的参数位于符号<<
和>>
之间。
echo=FALSE
隐藏代码,只显示代码的输出
cache=TRUE
如果cache被设置为TRUE,chunk不会每次执行都被运行。这在chunck中的数据没有改变的时候重新编译文档非常有用,可以节省编译时间。注意这个参数目前没有被Overleaf支持。文末的参考指南列出了更多可用的参数。
行内命令
你可以访问chunk生成的对象并且将它们显示出来。
例如:
\documentclass{article}
\begin{document}
You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:
<<echo=FALSE, cache=TRUE>>=
# Create a sequence of numbers
X = 2:10
# Display basic statistical measures
summary(X)
@
So, the mean of the data is $\Sexpr{mean(X)}$
\end{document}
命令\Sexpr{mean(X)}
将会在文档中输出R语言代码mean(X)
的结果。你可以在大括号中传输任意R语言代码。
绘图
你也可以在knitr文档中插入绘图。例如:
\documentclass{article}
\begin{document}
<<plot1, fig.pos="t", fig.height=4, fig.width=4, fig.cap="First plot">>=
xdata = read.csv(file="data.txt", head=TRUE,sep=" ")
hist(xdata$data, main="Overleaf histogram", xlab="Data")
@
The figure \ref{fig:plot1} is simple histogram.
\end{document}
这个直方图使用存储在''data.text''
中的数据。一些与绘图有关的命令被传输到chunk中。
plot1
这是用来引用某个绘图的标签。前缀fig:
是强制的。你可以在这个例子中看到绘图被引用为\ref{fig:plot1}
。
fig.pos=“t”
位置参数。与LaTeX中figure
环境的用法相同。
fig.height=4, fig.width=4
绘图的宽和高。
fig.cap=“First plot”
绘图的图题。
外部R语言代码文件
你可以从外部的R语言代码文件中引入代码。这一个特性非常有用。因为程序员经常在外部环境中调试好代码后,才将其引入到LaTeX文档中。
下面的代码存储在一个名为mycode.R
的文件中,我们将其中的代码引入到我们的LaTeX文档。
## ---- myrcode1
# Create a sequence of numbers
X = 2:10
## ---- myrcode2
# Display basic statistical measures
summary(X)
注意下面几行代码:
## ---- myrcode1
## ---- myrcode2
这些代码标识了代码chunk的开始并且是强制的。
The chunk below will not be printed
<<echo=FALSE, cache=FALSE>>=
read_chunk("mycode.R")
@
The code must show up here
<<myrcode2>>=
@
第一个chunk并不会被显示,只被用来导入文件中的代码,命令是read_chunk("mycode.R")
。参数echo=FALSE
因此设置为False
。此外,这些代码必须是不被缓存的(cached
)。在代码导入后,你可以使用### ----
之后所设置的标签来显示chunk内容。在这个例子中,标签是myrcode2
。
参考指南
一些chunk参数:
results
:改变由R代码语言所生成的内容的行为。markup
:输出使用LaTeX格式asis
:使用R语言的原始输出hold
:将所有的输出显示在chunk的末尾。hide
:隐藏所有输出。echo
:是否使用所有的R语言代码。可以接收其他参数,例如echo=2:3
只显示第二行到第三行的代码;echo=-2:-3
排除第二行到第三行的代码。cache
:是否缓存代码chunk。可选值是TRUE或FALSE。highlight
:是否高亮代码。可选值是TRUE或FALSE。background
:chunk的背景颜色,你可以使用rgb颜色或者HTML格式的颜色。默认值是#F7F7F7
。