R:xtable中的对角线列名

时间:2014-09-06 16:29:37

标签: r latex knitr pdflatex xtable

R-3.1.1,Win7 x64,knitr version 1.6,xtable version 1.7-3

我正在尝试根据讨论here中的想法构建一个带有角度列名的表格。我的工作流程建立在knitr / Latex之上,以自动化我的报告,因此我想将这些想法融入xtable中。我的代码如下:

\documentclass[a4paper,11pt]{article}

\usepackage{graphicx}
\usepackage[T1]{fontenc}
\usepackage{tabularx}
\usepackage{longtable}
\usepackage{rotating}
\usepackage{makecell}
\renewcommand{\rothead}[2][60]{\makebox[9mm][c]{\rotatebox{#1}{\makecell[c]{#2}}}}%


\begin{document}

<<global_opts, echo=FALSE>>=
opts_chunk$set(fig.keep='none', results='hide', echo=FALSE)
@

<<tab01>>=
require(xtable, quietly = TRUE)
test <- matrix(95:110, ncol = 4) 
rownames(test) <- paste0("row ", 1:4)
colnames(test) <- paste0("\\multicolumn{2}{c}{\\rotatebox{60}{column ", 1:4, "}}")
tab10 <- xtable(test)
tab10 <- print(tab10, sanitize.colnames.function = function(x){x})
@

{\Sexpr{tab10}}
\end{document}

这种方式可以完成工作,但不如我希望的那么好。输出如下:

enter image description here

当然,我希望列名称NEXT彼此相对,而不是彼此重叠。 另外,我收到以下警告:

knit2pdf("diagonal_headers.Rnw")

Warning message:
running command '"C:\PROGRA~1\MIKTEX~1.9\miktex\bin\x64\texi2dvi.exe" --quiet --pdf     "tab_tests_diagonaal.tex" --max-iterations=20 -I "C:/PROGRA~1/R/R-31~1.1/share/texmf/tex/latex" -I "C:/PROGRA~1/R/R-31~1.1/share/texmf/bibtex/bst"' had status 1 

总的来说,我越来越近了。如何修复表格布局?

1 个答案:

答案 0 :(得分:3)

这是完成任务的一种方法。前导码没有改变,所以我只在这里显示代码块。

代码的准系统版本是:

<<tab01_barebones>>=
require(xtable, quietly = TRUE)
test <- matrix(95:110, ncol = 4)
rownames(test) <- paste0("row ", 1:4)
cols <- paste0("\\rothead{column ", 1:4, "}", collapse = " & ")
cols <- paste0("\\rothead{} & ", cols, "\\\\")
tab10 <- xtable(test)
tab10 <- print(tab10, include.colnames = FALSE, add.to.row = list(pos = as.list(0), command = cols), sanitize.colnames.function = function(x) {x}, booktabs = FALSE, hline.after = NULL)
@

产生:

enter image description here

您的代码存在一些问题。实际上,您还需要行名称上方单元格的代码,这基本上是标题列中其他单元格的空白版本:\\multicolumn{1}{c}{\\rothead{}}。此外,\\multicolumn{2}必须是\\multicolumn{1},因为您实际上并不是合并单元格。事实上,您可以完全取消\\multicolumn{1}并保留\\rothead

您将看到布局变得有点笨拙,角度标题的b / c。这是让它更漂亮的一种方法:

<<tab01>>=
require(xtable, quietly = TRUE)
test <- matrix(95:110, ncol = 4)
rownames(test) <- paste0("row ", 1:4)
cols <- paste0("\\multicolumn{1}{c}{\\rothead{column ", 1:4, "}}", collapse = " & ")
cols <- paste0("\\multicolumn{1}{c}{\\rothead{}} & ", cols, "\\\\")
tab10 <- xtable(test)
align(tab10) <- "r|cccc|"
tab10 <- print(tab10, include.colnames = FALSE, add.to.row = list(pos = as.list(c(0,0,4)),     command = c(cols, "\\cline{2-5}","\\cline{2-5}")), 
           sanitize.colnames.function = function(x) {x}, booktabs = FALSE, hline.after = NULL)
@

我在这里恢复了\\multicolumn{1}所以垂直线不会延伸到标题单元格(b / c是丑陋的,带有这些有角度的标题)。我还添加了cline来生成部分水平线。结果表是:

enter image description here

使用align(tab10) <- "r|llll|"可能更好,尽管我不是左对齐数字的忠实粉丝:

enter image description here

HTH,彼得