如何在knitr文档中使用xtable默认绘制垂直线?

5

我希望knitr默认生成带有列之间垂直线的表格。

我知道可以传递align参数来打印xtable,但这很繁琐,并且不同列数的表格align的值是不同的。

如何使此成为默认行为,而不是为每个表格进行设置?

1个回答

4

你可以随时稍微修改 xtable ,以便动态构建 align 参数:

make_align_string <- function(x) {
  k <- ncol(x)
  format_str <- ifelse(sapply(x, is.numeric), "r", "l")
  paste0(c("r", format_str), collapse = "|")
}

xtable_custom <- function(x, ...) xtable(x, ..., align = make_align_string(x))

xtable_custom(head(iris))
% latex table generated in R 3.2.1 by xtable 1.8-0 package
% Mon Feb 15 14:58:39 2016
\begin{table}[ht]
\centering
\begin{tabular}{r|r|r|r|r|l}
  \hline
 & Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species \\ 
  \hline
1 & 5.10 & 3.50 & 1.40 & 0.20 & setosa \\ 
  2 & 4.90 & 3.00 & 1.40 & 0.20 & setosa \\ 
  3 & 4.70 & 3.20 & 1.30 & 0.20 & setosa \\ 
  4 & 4.60 & 3.10 & 1.50 & 0.20 & setosa \\ 
  5 & 5.00 & 3.60 & 1.40 & 0.20 & setosa \\ 
  6 & 5.40 & 3.90 & 1.70 & 0.40 & setosa \\ 
   \hline
\end{tabular}
\end{table}

这将破坏表格中的默认对齐方式(即字符串和数字的不同处理)。 - Rahul Gopinath
可以使用例如 as.numeric 轻松恢复它。 - tonytonov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接