Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make xtable draw the vertical lines by default in a knitr document

Tags:

r

knitr

xtable

I want knitr to produce tables with the vertical lines between columns by default.

I understand that I can pass align argument to print the xtable. But that is repetitive, and the value of align is not the same for tables with different number of columns.

How do I make this the default behavior rather than doing it for each table?

like image 516
Rahul Gopinath Avatar asked Sep 26 '22 09:09

Rahul Gopinath


1 Answers

You can always modify xtable a bit to construct the align argument on the fly:

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}
like image 109
tonytonov Avatar answered Sep 28 '22 05:09

tonytonov