问:如何在R&#39 {s} xtable
中修剪LaTeX表中的额外水平规则长度?
我想在下面的R代码中执行您所看到的操作。但是该代码会抛出错误,而不会产生预期的结果。
% table 1
\begin{table}[ht]
\centering
\begin{tabular}{@{}lrr@{}}
\toprule
& a\_a & b\_b \\
\midrule
A & 0.35 & -1.05 \\
B & 0.64 & 0.92 \\
\bottomrule
\end{tabular}
\end{table}
% table 2
\begin{table}[ht]
\centering
\begin{tabular}{lrr}
\toprule
& a\_a & b\_b \\
\midrule
A & 0.36 & -1.05 \\
B & 0.64 & 0.92 \\
\bottomrule
\end{tabular}
\end{table}
# Begin R code
library(xtable)
library(stringr)
options(xtable.comment = FALSE)
set.seed(10)
mat <- matrix(rnorm(4), nrow=2)
rownames(mat) <- LETTERS[1:2]
colnames(mat) <- str_c(letters[1:2], "_", letters[1:2])
#mat.x <- xtable(mat, caption="My Caption!", align="lrr", digits=2) # No Error!
mat.x <- xtable(mat, align="@{}lrr@{}", digits=2) # Error!
print(mat.x,
sanitize.text.function = function(x){x},
sanitize.colnames.function = function(x){str_replace_all(x, "_", "\\\\_")},
floating=T,
hline.after=NULL,
math.style.negative=F,
add.to.row=list(pos=list(-1,0,nrow(mat.x)),
command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
# Error in `align<-.xtable`(`*tmp*`, value = "@{}lrr@{}") :
# "align" must have length equal to 3 ( ncol(x) + 1 )
# In addition: Warning message:
# In .alignStringToVector(value) : Nonstandard alignments in align string
答案 0 :(得分:2)
您需要传递一个字符串,其字符数与列数+ 1相同,或者传递此长度的字符串。所以尝试(除了其他排列)
align=c("@{}l", "r", "r@{}")
看看为什么看看这些功能。
library(xtable)
set.seed(10)
mat <- matrix(rnorm(4), nrow=2)
rownames(mat) <- LETTERS[1:2]
colnames(mat) <- paste0(letters[1:2], "_", letters[1:2])
xtable(mat, align="@{}lrr@{}", digits=2)
“align”的长度必须等于3(ncol(x)+ 1)
警告建议传递长度为3的向量,请尝试
xtable(mat, align=c("@{}l","r", "r@{}"), digits=2)
# \begin{table}[ht]
# \centering
# \begin{tabular}{@{}lrr@{}}
# ---
# ---
这样可以正常工作。对齐参数对于传递字符串的方式也很稳健, 只要它具有所需的长度。
xtable(mat, align=c("@{}lrr@", "{", "}"), digits=2)
# \begin{table}[ht]
# \centering
# \begin{tabular}{@{}lrr@{}}
# ---
# ---
要了解为什么第一个字符串不起作用
查看xtable:::xtable.data.frame
函数的相关部分:必须与align
align(x) <- switch(1 + is.null(align), align, c("r", c("r", "l")[(characters | factors) + 1]))
这会导致xtable:::`align<-.xtable
,然后是xtable:::.alignStringToVector