使用表格+针织乳胶的简单示例 [英] Simple example of using tables + knitr for latex
问题描述
我正在使用表包,可打包文档中的示例太复杂了,它们对knitr
和Latex都不适合我.有人可以帮忙在表头显示带有一些公式和多行标签的简单表格吗?
I'm struggling with a tables package, all the examples in the packable docs are so complex and none of them works for me with knitr
and latex. Could somebody help be out and display a simple table with some formulas and multiline labels in the header?
类似这样的东西:
df <- data.frame(matrix(1:9, nrow = 3))
colnames(df) <- c("first column", "second \\frac{1}{2}", "third column first line \\ second line")
提前谢谢
推荐答案
可以使用xtable
包在LaTeX中为表创建多行标题.可以从.Rmd或.Rnw文件中编译这些文件.通过mattw建立示例,并对xtable
使用print
方法中的add.to.row
:
It is possible to create multi-line headers for tables in LaTeX using the xtable
package. These can be compiled from either .Rmd or .Rnw files. Building on the example by mattw and using add.to.row
in the print
method for xtable
:
df <- data.frame(matrix(1:50, nrow = 10))
print(
xtable(df),
include.rownames = FALSE,
include.colnames = FALSE,
add.to.row = list(
pos = list(0),
command = c(
"& \\multicolumn{4}{c}{4 column header} \\\\
\\cline{2-5}
col1 & col2 & col3 & col4 & col5 \\\\ "
)
)
)
请注意,add.to.row
需要一个包含两个元素的列表:pos和command.第一个必须是列表,第二个必须是字符串或向量,请参见?print.xtable
. pos
给出LaTeX插入的行号,而command
是插入.对此格式设置要格外小心,如果不使用空格或\n
,它将直接运行到第一列的下一个单元格中.
Note that add.to.row
requires a list with two elements: pos and command. The first must be a list, the second a character string or vector, see ?print.xtable
. pos
gives the row number for the LaTeX insertion, and command
is the insertion. Be a bit careful with formatting this, as it is will run directly into the next cell of the first column if you don't put in spaces or \n
.
有很多自定义选项,允许您通过一些调整来创建非常复杂的表.
There are lots of options for customisation, allowing you to create quite complex tables with a bit of tweaking.
print(
xtable(df),
include.rownames = FALSE,
include.colnames = FALSE,
hline.after = c(-1,0),
add.to.row = list(
pos = list(0,5,10),
command = c(
"& \\multicolumn{4}{c}{4 column header} \\\\
\\cline{2-5}
col1 & col2 & col3 & col4 & col5 \\\\ ",
"\\hline \\multicolumn{5}{l}{Separator in table.} \\\\ \\hline",
"\\hline \\multicolumn{5}{l}{Notes at end of table.} \\\\ "
)
)
)
在此示例中,我更改了xtable
放置\hline
的位置的默认设置,使我可以在注释上方添加最后一个\hline
-对解释表中的上标很有用.
In this example I change the default settings for where xtable
puts \hline
, allowing me to add the last \hline
above the notes - useful for explaining superscripts in the table.
还请注意使用\cline{2-5}
在第2-5列上给我一行.
Note also the use of \cline{2-5}
giving me a line over columns 2 - 5.
有关完全可复制的示例,请参见要点.
See gist for fully reproducible example.
这篇关于使用表格+针织乳胶的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!