1 %\VignetteIndexEntry{xtable Gallery}
\r
2 %\VignetteDepends{xtable}
\r
3 %\VignetteKeywords{LaTeX, HTML, table}
\r
4 %\VignettePackage{xtable}
\r
6 % \VignetteEngine{knitr::knitr}
\r
7 %**************************************************************************
\r
8 \documentclass{article}
\r
9 \usepackage[a4paper,height=24cm]{geometry}
\r
10 \usepackage{parskip}
\r
11 \usepackage{titlesec}
\r
12 \titleformat\subsubsection{\bfseries\itshape}{}{0pt}{}
\r
13 \usepackage{booktabs}
\r
14 \usepackage{longtable}
\r
15 \usepackage{rotating}
\r
17 \usepackage{tabularx}
\r
18 \newcommand\p{\vspace{2ex}}
\r
19 \setcounter{tocdepth}{2}
\r
20 %% Define \code \proglang and \pkg commands
\r
21 \newcommand\code[1]{\texttt{#1}}
\r
22 \newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}}
\r
23 \newcommand\proglang[1]{\textsf{#1}}
\r
25 \usepackage[hyphens]{url}
\r
26 \usepackage{hyperref}
\r
28 \usepackage{listings}
\r
29 \lstset{language = TeX, basicstyle = \ttfamily,
\r
30 keywordstyle = \ttfamily,
\r
31 emphstyle = \itshape,
\r
38 \title{The \pkg{xtable} Gallery}
\r
39 \author{Jonathan Swinton and others}
\r
46 \section{Introduction}
\r
47 \label{sec:introduction}
\r
49 This document gives a gallery of tables which can be made using the
\r
50 \pkg{xtable} package to create \LaTeX\ output. It doubles as a
\r
51 regression check for the package.
\r
56 opts_chunk$set(fig.path='figdir/fig', debug=TRUE, echo=TRUE)
\r
59 The first step is to load the package and set an option for this document.
\r
62 options(xtable.floating = FALSE)
\r
67 \subsection{Data frame}
\r
75 design.matrix <- model.matrix(~ sex*grade, data = tli[1:10, ])
\r
76 xtable(design.matrix, digits = 0)
\r
82 fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)
\r
89 fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)
\r
93 \subsubsection{Anova table (one model)}
\r
98 \subsubsection{Anova table (two models)}
\r
100 fm2b <- lm(tlimth ~ ethnicty, data = tli)
\r
101 xtable(anova(fm2b, fm2))
\r
106 <<results='asis'>>=
\r
107 fm3 <- glm(disadvg ~ ethnicty*grade, data = tli, family = binomial)
\r
112 <<results='asis'>>=
\r
116 \subsection{prcomp}
\r
117 <<results='asis'>>=
\r
118 pr1 <- prcomp(USArrests)
\r
123 <<results='asis'>>=
\r
124 xtable(summary(pr1))
\r
128 # pr2 <- princomp(USArrests)
\r
133 \subsection{Time series}
\r
134 <<results='asis'>>=
\r
135 temp.ts <- ts(cumsum(1 + round(rnorm(100), 0)),
\r
136 start = c(1954, 7), frequency = 12)
\r
137 temp.table <- xtable(temp.ts, digits = 0)
\r
142 # ## Demonstrate saving to file
\r
143 # for(i in c("latex", "html")) {
\r
144 # outFileName <- paste("xtable.", ifelse(i=="latex", "tex", i), sep = "")
\r
145 # print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,
\r
146 # latex.environments = NULL)
\r
147 # print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,
\r
148 # latex.environments = "")
\r
149 # print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,
\r
150 # latex.environments = "center")
\r
151 # print(xtable(anova(glm.D93, test = "Chisq")),
\r
152 # type = i, file = outFileName,
\r
154 # print(xtable(anova(glm.D93)), hline.after = c(1),
\r
155 # size = "small", type = i,
\r
156 # file = outFileName, append = TRUE)
\r
157 # # print(xtable(pr2), type = i, file = outFileName, append = TRUE)
\r
162 \section{Helper functions for formatting}
\r
163 The functions \code{xalign}, \code{xdigits}, and \code{xdisplay} are useful for
\r
164 formatting tables in a sensible way. Consider the output produced by the default
\r
167 <<results='asis'>>=
\r
168 dat <- mtcars[1:3, 1:6]
\r
174 Now change the default alignment, digits and display using helper functions
\r
175 \code{xalign}, \code{xdigits}, and \code{xdisplay}. This produces a better
\r
176 format as shown below.
\r
178 <<results='asis'>>=
\r
179 align(x) <- xalign(x)
\r
180 digits(x) <- xdigits(x)
\r
181 display(x) <- xdisplay(x)
\r
187 \section{Sanitization}
\r
188 <<results='asis'>>=
\r
189 insane <- data.frame(Name = c("Ampersand","Greater than","Less than",
\r
190 "Underscore","Per cent","Dollar",
\r
191 "Backslash","Hash","Caret","Tilde",
\r
192 "Left brace","Right brace"),
\r
193 Character = I(c("&",">","<","_","%","$",
\r
194 "\\","#","^","~","{","}")))
\r
195 colnames(insane)[2] <- paste(insane[, 2], collapse = "")
\r
200 Sometimes you might want to have your own sanitization function.
\r
202 <<results='asis'>>=
\r
203 wanttex <- xtable(data.frame(Column =
\r
204 paste("Value_is $10^{-",1:3,"}$", sep = "")))
\r
205 print(wanttex, sanitize.text.function =
\r
206 function(str) gsub("_", "\\_", str, fixed = TRUE))
\r
211 \subsection{Markup in tables}
\r
212 Markup can be included in tables, including in column and row names, by using
\r
213 a custom \code{sanitize.text.function}.
\r
215 <<results='asis'>>=
\r
216 mat <- round(matrix(c(0.9, 0.89, 200, 0.045, 2.0), c(1, 5)), 4)
\r
217 rownames(mat) <- "$y_{t-1}$"
\r
218 colnames(mat) <- c("$R^2$", "$\\bar{x}$", "F-stat", "S.E.E", "DW")
\r
220 print(mat, sanitize.text.function = function(x) {x})
\r
224 % By David Dahl to demonstrate contribution from David Whitting, 2007-10-09.
\r
226 You can also have sanitize functions that are specific to column or
\r
227 row names. In the table below, the row name is not sanitized but
\r
228 column names and table elements are.
\r
230 <<results='asis'>>=
\r
231 money <- matrix(c("$1,000","$900","$100"), ncol = 3,
\r
232 dimnames = list("$\\alpha$",
\r
233 c("Income (US$)","Expenses (US$)",
\r
235 print(xtable(money), sanitize.rownames.function = function(x) {x})
\r
238 \section{Format examples}
\r
239 \subsection{Adding a centering environment}
\r
240 <<results='asis'>>=
\r
241 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"\""),
\r
242 floating = TRUE, latex.environments = "")
\r
243 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"center\""),
\r
244 floating = TRUE, latex.environments = "center")
\r
249 \subsection{Column alignment}
\r
250 <<results='asis'>>=
\r
251 tli.table <- xtable(tli[1:10, ])
\r
252 align(tli.table) <- rep("r", 6)
\r
256 \subsubsection{Left aligned strings with column lines}
\r
257 <<results='asis'>>=
\r
258 align(tli.table) <- "|rrl|l|lr|"
\r
262 \subsubsection{Fixed width columns}
\r
263 <<results='asis'>>=
\r
264 align(tli.table) <- "|rr|lp{3cm}l|r|"
\r
270 \subsection{Number of digits}
\r
271 One number for all columns,
\r
272 <<results='asis'>>=
\r
273 display(tli.table)[c(2,6)] <- "f"
\r
274 digits(tli.table) <- 3
\r
279 or one for each column, including the row names,
\r
280 <<results='asis'>>=
\r
281 digits(tli.table) <- 1:(ncol(tli)+1)
\r
286 or as a full matrix.
\r
287 <<results='asis'>>=
\r
288 digits(tli.table) <- matrix(0:4, nrow = 10, ncol = ncol(tli)+1)
\r
294 \subsection{Suppress row/column names}
\r
295 \subsubsection{Suppress row names}
\r
296 <<results='asis'>>=
\r
297 tli.table <- xtable(tli[1:10, ])
\r
298 print(tli.table, include.rownames = FALSE)
\r
302 If you want a vertical line on the left, you need to change the \code{align}
\r
304 <<results='asis'>>=
\r
305 align(tli.table) <- "|r|r|lp{3cm}l|r|"
\r
306 print(tli.table, include.rownames = FALSE)
\r
310 Revert the alignment to what is was before.
\r
312 align(tli.table) <- "|rr|lp{3cm}l|r|"
\r
317 \subsubsection{Suppress column names}
\r
318 <<results='asis'>>=
\r
319 print(tli.table, include.colnames = FALSE)
\r
323 Note the doubled header lines which can be suppressed.
\r
324 <<results='asis'>>=
\r
325 print(tli.table, include.colnames = FALSE,
\r
326 hline.after = c(0,nrow(tli.table)))
\r
329 \subsubsection{Suppress row and column names}
\r
330 <<results='asis'>>=
\r
331 print(tli.table, include.colnames = FALSE, include.rownames = FALSE)
\r
336 \subsection{Rotate row/column names}
\r
337 The \code{rotate.rownames} and \code{rotate.colnames} arguments can be used to
\r
338 rotate the row and/or column names. This requires \verb|\usepackage{rotating}|
\r
339 in the \LaTeX\ preamble.
\r
341 <<results='asis'>>=
\r
342 print(tli.table, rotate.rownames = TRUE, rotate.colnames = TRUE)
\r
347 \subsection{Horizontal lines}
\r
348 \subsubsection{Line locations}
\r
349 Use the \code{hline.after} argument to specify the position of the
\r
352 <<results='asis'>>=
\r
353 print(xtable(anova(fm3)), hline.after = c(1))
\r
356 \subsubsection{Line styles}
\r
357 Specifying \code{booktabs = TRUE} will generate three line types. By default,
\r
358 when no value is given for \code{hline.after}, a \verb|\toprule| will be drawn
\r
359 above the table, a \verb|\midrule| after the table headings and a
\r
360 \verb|\bottomrule| below the table. This requires \verb|\usepackage{booktabs}|
\r
361 in the \LaTeX\ preamble.
\r
364 The top and bottom rules are slightly thicker than the mid rule. The thickness
\r
365 of the lines can be set via the \LaTeX\ lengths \verb|\heavyrulewidth| and
\r
366 \verb|\lightrulewidth|.
\r
368 <<results='asis'>>=
\r
369 tli.table <- xtable(tli[1:10, ])
\r
370 print(tli.table, include.rownames = FALSE, booktabs = TRUE)
\r
374 If \code{hline.after} includes \code{-1}, a \verb|\toprule| will be
\r
375 drawn above the table. If \code{hline.after} includes the number of
\r
376 rows in the table, a \verb|\bottomrule| will be drawn below the
\r
377 table. For any other values specified in \code{hline.after}, a
\r
378 \verb|\midrule| will be drawn after that line of the table.
\r
381 The following table has more than one \verb|\midrule|.
\r
383 <<results='asis'>>=
\r
384 bktbs <- xtable(matrix(1:10, ncol = 2))
\r
385 hlines <- c(-1, 0, 1, nrow(bktbs))
\r
386 print(bktbs, booktabs = TRUE, hline.after = hlines)
\r
389 \subsection{Table level commands}
\r
390 <<results='asis'>>=
\r
391 print(xtable(anova(fm3)), size = "large")
\r
395 <<results='asis'>>=
\r
396 print(xtable(anova(fm3)), size = "\\setlength{\\tabcolsep}{12pt}")
\r
399 \subsection{Long tables}
\r
400 Requires \verb|\usepackage{longtable}| in the \LaTeX\ preamble.
\r
402 <<results='asis'>>=
\r
403 x <- matrix(rnorm(1000), ncol = 10)
\r
404 x.big <- xtable(x, caption = 'A \\code{longtable} spanning several pages')
\r
405 print(x.big, hline.after=c(-1, 0), tabular.environment = 'longtable')
\r
408 %% The column name alignment is off in the following example.
\r
409 %% It needs some revision before exposing it. - CR, 7/2/2012
\r
411 %% Tried to fix this and got some of the way, but \hlines are wrong
\r
412 %% and first column is too wide. - DJS 4/10/2014
\r
413 %% \subsubsection{Long tables with the header on each page}
\r
414 %% The \code{add.to.row} argument can be used to display the header
\r
415 %% for a long table on each page, and to add a "continued" footer
\r
416 %% on all pages except the last page.
\r
418 %% \newcommand{\head}[1]{\centercell{\bfseries#1}}
\r
420 %% <<results='asis'>>=
\r
421 %% x <- matrix(rnorm(1000), ncol = 10)
\r
422 %% hdr <- paste(paste("\\multicolumn{1}{c}{",1:9,"} & ", collapse = ""),
\r
423 %% "\\multicolumn{1}{c}{10}\\\\")
\r
424 %% addtorow <- list()
\r
425 %% addtorow$pos <- list()
\r
426 %% addtorow$pos[[1]] <- c(0)
\r
427 %% addtorow$command <- c(paste(
\r
430 %% " \\endhead \n",
\r
432 %% " {\\footnotesize Continued on next page} \n",
\r
433 %% " \\endfoot \n",
\r
434 %% " \\endlastfoot \n", sep = ""))
\r
435 %% x.big2 <- xtable(x, label = "tabbig2", align = "lrrrrrrrrrr",
\r
436 %% caption = "Example of longtable with the header on each page")
\r
437 %% print(x.big2, tabular.environment = "longtable",
\r
438 %% include.rownames = FALSE, include.colnames = FALSE,
\r
439 %% add.to.row = addtorow)
\r
442 \subsection{Use of \code{add.to.row} argument}
\r
443 Here is an example of the use of the \code{add.to.row} argument, taken
\r
444 from a question on Stack Exchange:
\r
445 \url{http://stackoverflow.com/questions/19846796/adding-titles-to-xtable}.
\r
448 Grade3 <- c("A","B","B","A","B","C","C","D","A","B",
\r
449 "C","C","C","D","B","B","D","C","C","D")
\r
450 Grade6 <- c("A","A","A","B","B","B","B","B","C","C",
\r
451 "A","C","C","C","D","D","D","D","D","D")
\r
452 Cohort <- table(Grade3,Grade6)
\r
453 rownames(Cohort) <- 1:4
\r
454 colnames(Cohort) <- 5:8
\r
456 addtorow$pos <- list()
\r
457 addtorow$pos[[1]] <- 0
\r
458 addtorow$pos[[2]] <- 0
\r
459 addtorow$command <- c('& \\multicolumn{4}{c}{Grade 6} \\\\\n',
\r
460 "Grade 3 & A & B & C & D \\\\\n")
\r
461 print(xtable(Cohort, caption = 'My Title'), caption.placement = 'bottom',
\r
462 add.to.row = addtorow, include.colnames = FALSE,
\r
467 <<printaddtorow, echo = FALSE, results = 'asis'>>=
\r
468 print(xtable(Cohort, caption = 'My Title'), caption.placement = 'bottom',
\r
469 add.to.row = addtorow, include.colnames = FALSE,
\r
473 \subsection{Sideways tables}
\r
474 Requires \verb|\usepackage{rotating}| in the LaTeX
\r
475 preamble. Sideways tables can't be forced in place with the \code{[H]}
\r
476 specifier, but you can use the \verb|\clearpage| command to get them
\r
479 <<results='asis'>>=
\r
481 x.side <- xtable(x, caption = 'A sideways table')
\r
482 print(x.side, floating = TRUE, floating.environment = 'sidewaystable')
\r
486 \subsection{Rescaled tables}
\r
487 Specify a \code{scalebox} value to rescale the table.
\r
488 <<results='asis'>>=
\r
490 x.rescale <- xtable(x)
\r
491 print(x.rescale, scalebox = 0.7)
\r
494 \subsection{Aligning Fixed Width Columns}
\r
496 Note that using specifications such as \lstinline+p{2cm}+ always
\r
497 produces a \textbf{left aligned} column. What if some other alignment
\r
500 This is not really a problem with \pkg{xtable} but with the formatting
\r
501 of tables with fixed width columns and different alignments using
\r
504 This question appears on Stack Exchange:\\
\r
505 \url{http://tex.stackexchange.com/questions/12703/how-to-create-fixed-width-table-columns-with-text-raggedright-centered-raggedlef}
\r
507 The response is to use the \lstinline+array+ package, defining new
\r
511 \newcolumntype{L}[1]{>{\raggedright\let\newline\\
\r
512 \arraybackslash\hspace{0pt}}m{#1}}
\r
513 \newcolumntype{C}[1]{>{\centering\let\newline\\
\r
514 \arraybackslash\hspace{0pt}}m{#1}}
\r
515 \newcolumntype{R}[1]{>{\raggedleft\let\newline\\
\r
516 \arraybackslash\hspace{0pt}}m{#1}}
\r
517 \newcolumntype{P}[1]{>{\raggedright\tabularxbackslash}p{#1}}
\r
520 These allow for very sophisticated cell formatting, namely
\r
521 left-aligned, centred, or right-aligned text, with recognition of line
\r
522 breaks for the first three new column types. If these lines are
\r
523 included along with \lstinline+\usepackage{array}+, then the following
\r
526 \newcolumntype{L}[1]{>{\raggedright\let\newline\\
\r
527 \arraybackslash\hspace{0pt}}m{#1}}
\r
528 \newcolumntype{C}[1]{>{\centering\let\newline\\
\r
529 \arraybackslash\hspace{0pt}}m{#1}}
\r
530 \newcolumntype{R}[1]{>{\raggedleft\let\newline\\
\r
531 \arraybackslash\hspace{0pt}}m{#1}}
\r
532 \newcolumntype{P}[1]{>{\raggedright\tabularxbackslash}p{#1}}
\r
535 df <- data.frame(name = c("A","B"),
\r
536 right = c(1.4, 34.6),
\r
537 left = c(1.4, 34.6),
\r
538 text = c("txt1","txt2"))
\r
541 Here is the output produced by printing an
\r
542 \lstinline+"xtable"+ object.
\r
545 print(xtable(df, align = c("|l", "|c", "|R{3cm}","|L{3cm}","| p{3cm}|")),
\r
546 floating = FALSE, include.rownames = FALSE)
\r
550 Using the \pkg{knitr} option \code{'asis'} we obtain the table.
\r
552 <<arrayprint, results = 'asis'>>=
\r
553 print(xtable(df, align = c("|l", "|c", "|R{3cm}","|L{3cm}","| p{3cm}|")),
\r
554 floating = FALSE, include.rownames = FALSE)
\r
560 \subsection{Table width}
\r
561 The \code{tabularx} environment is for typesetting tables whose overall width is
\r
562 fixed. The column alignment code \code{X} denotes columns that will be stretched
\r
563 to achieve the desired table width. Requires \verb|\usepackage{tabularx}| in the
\r
566 <<results='asis'>>=
\r
567 df.width <- data.frame(One = c("item 1", "A"), Two = c("item 2", "B"),
\r
568 Three = c("item 3", "C"), Four = c("item 4", "D"))
\r
569 x.width <- xtable(df.width)
\r
570 align(x.width) <- "|l|X|l|l|l|"
\r
571 print(x.width, tabular.environment = "tabularx", width = "\\textwidth")
\r
576 \section{Suppressing printing}
\r
577 By default the \code{print} method will print the \LaTeX\ or HTML to standard
\r
578 output and also return the character strings invisibly. The printing to
\r
579 standard output can be suppressed by specifying \code{print.results = FALSE}.
\r
582 x.out <- print(tli.table, print.results = FALSE)
\r
585 Formatted output can also be captured without printing with the
\r
586 \code{toLatex} method. This function returns an object of class
\r
590 x.ltx <- toLatex(tli.table)
\r
595 \section{Acknowledgements}
\r
596 Most of the examples in this gallery are taken from the \pkg{xtable}
\r
599 \section{\proglang{R} session information}
\r
600 <<results='asis'>>=
\r
601 toLatex(sessionInfo())
\r