我想要自定义导出到LaTeX的xtable。我知道这里有一些关于xtable的问题,但我找不到我正在寻找的具体东西。
下面是我的表可能是什么样子的示例:
my.table <- data.frame(Specifiers=c("","Spec1", "Spec2", "Spec3"),
Values1 = c("N=10", 1.03, 1.71, 2.25),
Values2 = c("N=20", 1.32, 1.79, 2.43))
colnames(my.table)[1] <- ""这将创建:
Values1 Values2
1 N=10 N=20
2 Spec1 1.03 1.32
3 Spec2 1.71 1.79
4 Spec3 2.25 2.43实际上,此表是通过my.table <- read.delim("filename.csv", sep=",", header=TRUE)以data.frame格式从.csv文件导入的
现在,我使用xtable创建一个LaTeX表
latex.tab <- xtable(my.table, caption=c("Stats"))
print(latex.tab, file="Summarystats.tex",
floating.environment='sidewaystable',
include.rownames=FALSE,
booktabs=TRUE,
latex.environment=NULL)以下是生成的LaTeX代码:
\begin{sidewaystable}[ht]
\begin{tabular}{lllllll}
\toprule
& Values1 & Values2 \\
\midrule
N=10 & N=20 \\
Spec1 & 1.03 & 1.32 \\
Spec2 & 1.71 & 1.79 \\
Spec3 & 2.25 & 2.43 \\
\bottomrule
\end{tabular}
\end{sidewaystable}好的,下面是我想要改变的:
1)在第二行之后而不是第一行之后插入\midrule。2)通过在sidewaystable (或普通table)环境中插入\rowcolors{2}{gray!25}{white}来改变该表中各行的颜色。3)将列名旋转45°4)当我想要使表格居中时,插入\centering而不是center-environment。
对如何实现这一点有什么想法吗?
发布于 2012-11-11 07:40:14
您需要一些预处理,传递给print.xtable的额外参数和一些后处理:
my.table <- data.frame(Specifiers=c("","Spec1", "Spec2", "Spec3"),
Values1 = c("N=10", 1.03, 1.71, 2.25),
Values2 = c("N=20", 1.32, 1.79, 2.43))
colnames(my.table)[1] <- ""
# Pre-processing: rotates column names by 45 degrees
head = apply(as.array(names(my.table)), 1, function(x) paste("\\rotatebox{45}{", x, "}"))
head = paste(head, c(rep("&", length(head)-1), "\\\\\n"), collapse="")
latex.tab <- xtable(my.table, caption=c("Stats"))
ltable = print(latex.tab, file="", # File is empty, post-processing needed
floating.environment='sidewaystable',
include.rownames=FALSE,
include.colnames=FALSE, # No colnames
booktabs=TRUE,
latex.environment="center", # Or NULL
# Adds some extra-text after the rows specified in pos.
# Adds new \midrule and comments old one.
# Adds pre-processed names of columns
add.to.row=list(pos=as.list(c(0, 0, 1)), command=as.vector(c(head, "%", "\\midrule\n"))))
# Post-processing: replaces \begin{center} with \centering
ltable = sub("\\begin{center}\n", "\\centering\n", ltable, fixed=TRUE)
ltable = sub("\\end{center}\n", "\n", ltable, fixed=TRUE)
# Post-processing: adds alternating colours
ltable = sub("\\begin{tabular}",
"\\rowcolors{2}{gray!25}{white}\n\\begin{tabular}",
ltable, fixed=TRUE)
# Writes output to the file
cat(ltable, file="Summarystats.tex")如果您需要tabular之外的其他选项卡环境,可以1)添加新变量:
TABULAR = "tabular"2)将其值传递给print.xtable,如下所示:
...
tabular.environment=TABULAR,
...3)更改交替颜色的后处理:
ltable = sub(sprintf("\\begin{%s}", TABULAR),
sprintf("\\rowcolors{2}{gray!25}{white}\n\\begin{%s}", TABULAR),
ltable, fixed=TRUE)结果:

https://stackoverflow.com/questions/11777586
复制相似问题