]> git.donarmstrong.com Git - xtable.git/blob - pkg/vignettes/xtableGallery.Rnw
Minor changes to vignettes. Also added documentation for flat tables.
[xtable.git] / pkg / vignettes / xtableGallery.Rnw
1 %\VignetteIndexEntry{xtable Gallery}\r
2 %\VignetteDepends{xtable}\r
3 %\VignetteKeywords{LaTeX, HTML, table}\r
4 %\VignettePackage{xtable}\r
5 % !Rnw weave = knitr\r
6 % \VignetteEngine{knitr::knitr}\r
7 %**************************************************************************\r
8 \documentclass{article}\r
9 \usepackage[a4paper,height=24cm]{geometry} % geometry first\r
10 \usepackage{array}\r
11 \usepackage{booktabs}\r
12 \usepackage{longtable}\r
13 \usepackage{parskip}\r
14 \usepackage{rotating}\r
15 \usepackage{tabularx}\r
16 \usepackage{titlesec}\r
17 \usepackage{hyperref} % hyperref last\r
18 \titleformat\subsubsection{\bfseries\itshape}{}{0pt}{}\r
19 \newcommand\p{\vspace{2ex}}\r
20 \newcommand\code[1]{\texttt{#1}}\r
21 \newcommand\pkg[1]{\textbf{#1}}\r
22 \setcounter{tocdepth}{2}\r
23 \begin{document}\r
24 \r
25 \title{The \pkg{xtable} Gallery}\r
26 \author{Jonathan Swinton and others}\r
27 \maketitle\r
28 \r
29 \tableofcontents\r
30 \r
31 \newpage\r
32 \r
33 \section{Introduction}\r
34 This document gives a gallery of tables which can be made using the\r
35 \pkg{xtable} package to create \LaTeX\ output. It doubles as a\r
36 regression check for the package.\r
37 \r
38 <<include=FALSE>>=\r
39 library(knitr)\r
40 opts_chunk$set(fig.path='figdir/fig', debug=TRUE, echo=TRUE)\r
41 set.seed(1234)\r
42 @\r
43 \r
44 The first step is to load the package and set an option for this document.\r
45 <<results='asis'>>=\r
46 library(xtable)\r
47 options(xtable.floating = FALSE)\r
48 options(xtable.timestamp = "")\r
49 @\r
50 \r
51 \section{Gallery}\r
52 \subsection{Data frame}\r
53 <<results='asis'>>=\r
54 data(tli)\r
55 xtable(tli[1:10, ])\r
56 @\r
57 \r
58 \subsection{Matrix}\r
59 <<results='asis'>>=\r
60 design.matrix <- model.matrix(~ sex*grade, data = tli[1:10, ])\r
61 xtable(design.matrix, digits = 0)\r
62 @\r
63 \r
64 \newpage\r
65 \subsection{aov}\r
66 <<results='asis'>>=\r
67 fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)\r
68 xtable(fm1)\r
69 @\r
70 \r
71 \subsection{lm}\r
72 <<results='asis'>>=\r
73 fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)\r
74 xtable(fm2)\r
75 @\r
76 \r
77 \subsubsection{Anova table (one model)}\r
78 <<results='asis'>>=\r
79 xtable(anova(fm2))\r
80 @\r
81 \r
82 \subsubsection{Anova table (two models)}\r
83 <<results='asis'>>=\r
84 fm2b <- lm(tlimth ~ ethnicty, data = tli)\r
85 xtable(anova(fm2b, fm2))\r
86 @\r
87 \r
88 \subsubsection{Anova list}\r
89 \r
90 <<aovlist>>=\r
91 Block <- gl(8, 4)\r
92 A <- factor(c(0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,\r
93               0,1,0,1,0,1,0,1,0,1,0,1))\r
94 B <- factor(c(0,0,1,1,0,0,1,1,0,1,0,1,1,0,1,0,0,0,1,1,\r
95               0,0,1,1,0,0,1,1,0,0,1,1))\r
96 C <- factor(c(0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,1,0,1,0,1,\r
97               1,0,1,0,0,0,1,1,1,1,0,0))\r
98 Yield <- c(101, 373, 398, 291, 312, 106, 265, 450, 106, 306, 324, 449,\r
99            272, 89, 407, 338, 87, 324, 279, 471, 323, 128, 423, 334,\r
100            131, 103, 445, 437, 324, 361, 302, 272)\r
101 aovdat <- data.frame(Block, A, B, C, Yield)\r
102 \r
103 old <- getOption("contrasts")\r
104 options(contrasts = c("contr.helmert", "contr.poly"))\r
105 (fit <- aov(Yield ~ A*B*C + Error(Block), data = aovdat))\r
106 class(fit)\r
107 summary(fit)\r
108 options(contrasts = old)\r
109 @\r
110 \r
111 \p\r
112 \r
113 <<xtableaovlist, results='asis'>>=\r
114 xtable(fit)\r
115 @\r
116 \r
117 \r
118 \newpage\r
119 \subsection{glm}\r
120 <<results='asis'>>=\r
121 fm3 <- glm(disadvg ~ ethnicty*grade, data = tli, family = binomial)\r
122 xtable(fm3)\r
123 @\r
124 \r
125 \subsubsection{Analysis of deviance}\r
126 <<results='asis'>>=\r
127 xtable(anova(fm3))\r
128 @\r
129 \r
130 \subsection{prcomp}\r
131 <<results='asis'>>=\r
132 pr1 <- prcomp(USArrests)\r
133 xtable(pr1)\r
134 @\r
135 \r
136 \p\r
137 <<results='asis'>>=\r
138 xtable(summary(pr1))\r
139 @\r
140 \r
141 <<include=FALSE>>=\r
142 # pr2 <- princomp(USArrests)\r
143 # xtable(pr2)\r
144 @\r
145 \r
146 \newpage\r
147 \r
148 \subsection{Time series}\r
149 <<results='asis'>>=\r
150 temp.ts <- ts(cumsum(1 + round(rnorm(100), 0)),\r
151               start = c(1954, 7), frequency = 12)\r
152 temp.table <- xtable(temp.ts, digits = 0)\r
153 temp.table\r
154 @\r
155 \r
156 \subsection{Flat tables}\r
157 \label{sec:flat-tables}\r
158 \r
159 See the \textbf{Details} section of the help for \code{ftable} for a\r
160 description of these tables, which are flat versions of\r
161 multi-dimensional contingency tables. They require special methods to\r
162 enable them to be printed using \pkg{xtable}\r
163 \r
164 \r
165 <<ftable>>=\r
166 data(mtcars)\r
167 mtcars$cyl <- factor(mtcars$cyl, levels = c("4","6","8"),\r
168                      labels = c("four","six","eight"))\r
169 tbl <- ftable(mtcars$cyl, mtcars$vs, mtcars$am, mtcars$gear,\r
170               row.vars = c(2, 4),\r
171               dnn = c("Cylinders", "V/S", "Transmission", "Gears"))\r
172 \r
173 \r
174 @ %def\r
175 \r
176 \p\r
177 <<ftablecheck>>=\r
178 xftbl <- xtableFtable(tbl, method = "compact")\r
179 print.xtableFtable(xftbl, booktabs = TRUE)\r
180 @ %def\r
181 <<ftable1, results = 'asis'>>=\r
182 xftbl <- xtableFtable(tbl)\r
183 print.xtableFtable(xftbl)\r
184 @ %def\r
185 \r
186 \p\r
187 <<ftable2, results = 'asis'>>=\r
188 xftbl <- xtableFtable(tbl, method = "row.compact")\r
189 print.xtableFtable(xftbl, rotate.colnames = TRUE,\r
190                    rotate.rownames = TRUE)\r
191 @ %def\r
192 \r
193 \p\r
194 <<ftable3, results = 'asis'>>=\r
195 xftbl <- xtableFtable(tbl, method = "col.compact")\r
196 print.xtableFtable(xftbl, rotate.rownames = TRUE)\r
197 @ %def\r
198 \r
199 \p\r
200 Booktabs is incompatible with vertical lines in tables, so the\r
201 vertical dividing line is removed.\r
202 <<ftable4, results = 'asis'>>=\r
203 xftbl <- xtableFtable(tbl, method = "compact")\r
204 print.xtableFtable(xftbl, booktabs = TRUE)\r
205 @ %def\r
206 \r
207 \newpage\r
208 \r
209 <<include=FALSE>>=\r
210 # ## Demonstrate saving to file\r
211 # for(i in c("latex", "html")) {\r
212 #   outFileName <- paste("xtable.", ifelse(i=="latex", "tex", i), sep = "")\r
213 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
214 #         latex.environments = NULL)\r
215 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
216 #         latex.environments = "")\r
217 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
218 #         latex.environments = "center")\r
219 #   print(xtable(anova(glm.D93, test = "Chisq")),\r
220 #         type = i, file = outFileName,\r
221 #         append = TRUE)\r
222 #   print(xtable(anova(glm.D93)), hline.after = c(1),\r
223 #         size = "small", type = i,\r
224 #         file = outFileName, append = TRUE)\r
225 #   # print(xtable(pr2), type = i, file = outFileName, append = TRUE)\r
226 # }\r
227 @\r
228 \r
229 \section{Automatic formatting}\r
230 \subsection{Suggest alignment, digits, and display}\r
231 The functions \code{xalign}, \code{xdigits}, and \code{xdisplay} are\r
232 useful for formatting tables in a sensible way. Consider the output\r
233 produced by the default formatting.\r
234 \r
235 <<results='asis'>>=\r
236 dat <- mtcars[1:3, 1:6]\r
237 x <- xtable(dat)\r
238 x\r
239 @\r
240 \r
241 \p\r
242 Now change the default alignment, digits and display using helper functions\r
243 \code{xalign}, \code{xdigits}, and \code{xdisplay}. This produces a better\r
244 format as shown below.\r
245 \r
246 <<results='asis'>>=\r
247 align(x) <- xalign(x)\r
248 digits(x) <- xdigits(x)\r
249 display(x) <- xdisplay(x)\r
250 x\r
251 @\r
252 \r
253 \subsection{Shorthand notation}\r
254 For convenience, the three `autoformat' functions (\code{xalign},\r
255 \code{xdigits}, and \code{xdisplay}) can be applied together when an\r
256 \code{xtable} is created, using the \code{auto} argument:\r
257 \r
258 <<results='asis'>>=\r
259 xtable(dat, auto = TRUE)\r
260 @\r
261 \r
262 \p\r
263 Similarly, the \code{autoformat} function can be used to postprocess an\r
264 existing \code{xtable}:\r
265 \r
266 <<results='asis'>>=\r
267 x <- xtable(dat)\r
268 autoformat(x)\r
269 @\r
270 \r
271 \newpage\r
272 \r
273 \subsection{Math-Style Exponents}\r
274 If you prefer $5 \times 10^5$ in your tables to 5e5, the\r
275 \code{math.style.exponents} option to \code{print.xtable} is useful:\r
276 \r
277 <<results='asis'>>=\r
278 print(xtable(data.frame(text = c("foo","bar"),\r
279                         googols = c(10e10,50e10),\r
280                         small = c(8e-24,7e-5),\r
281                         row.names = c("A","B")),\r
282              display = c("s","s","g","g")),\r
283       math.style.exponents = TRUE)\r
284 @\r
285 \r
286 this option also supports the values \code{ensuremath} which uses\r
287 \code{\char`\\ensuremath} instead of \code{\$\$} and \code{UTF-8}\r
288 which uses UTF-8 to approximate the \LaTeX typesetting.\r
289 \r
290 \r
291 \section{Sanitization}\r
292 <<results='asis'>>=\r
293 insane <- data.frame(Name = c("Ampersand","Greater than","Less than",\r
294                             "Underscore","Per cent","Dollar",\r
295                             "Backslash","Hash","Caret","Tilde",\r
296                             "Left brace","Right brace"),\r
297                      Character = I(c("&",">","<","_","%","$",\r
298                                      "\\","#","^","~","{","}")))\r
299 colnames(insane)[2] <- paste(insane[, 2], collapse = "")\r
300 xtable(insane)\r
301 @\r
302 \r
303 \p\r
304 Sometimes you might want to have your own sanitization function.\r
305 \r
306 \r
307 <<results='asis'>>=\r
308 wanttex <- xtable(data.frame(Column =\r
309                              paste("Value_is $10^{-",1:3,"}$", sep = "")))\r
310 print(wanttex, sanitize.text.function =\r
311       function(str) gsub("_", "\\_", str, fixed = TRUE))\r
312 @\r
313 \r
314 \p\r
315 Sanitization can be useful in formatting column headings and row names:\r
316 \r
317 <<sanitize3>>=\r
318 dat <- mtcars[1:3, 1:6]\r
319 large <- function(x){\r
320   paste0('{\\Large{\\bfseries ', x, '}}')\r
321 }\r
322 italic <- function(x){\r
323   paste0('{\\emph{ ', x, '}}')\r
324 }\r
325 @ %def\r
326 \r
327 <<sanitize4, results = 'asis'>>=\r
328 print(xtable(dat),\r
329       sanitize.rownames.function = italic,\r
330       sanitize.colnames.function = large,\r
331       booktabs = TRUE)\r
332 @ %def\r
333 \r
334 \r
335 \r
336 \newpage\r
337 \r
338 \subsection{Markup in tables}\r
339 Markup can be included in tables, including in column and row names,\r
340 by using a custom \code{sanitize.text.function}.\r
341 \r
342 <<results='asis'>>=\r
343 mat <- round(matrix(c(0.9, 0.89, 200, 0.045, 2.0), c(1, 5)), 4)\r
344 rownames(mat) <- "$y_{t-1}$"\r
345 colnames(mat) <- c("$R^2$", "$\\bar{x}$", "F-stat", "S.E.E", "DW")\r
346 mat <- xtable(mat)\r
347 print(mat, sanitize.text.function = function(x) {x})\r
348 @\r
349 \r
350 % By David Dahl to demonstrate contribution from David Whitting, 2007-10-09.\r
351 \p\r
352 You can also have sanitize functions that are specific to column or\r
353 row names.  In the table below, the row name is not sanitized but\r
354 column names and table elements are.\r
355 \r
356 <<results='asis'>>=\r
357 money <- matrix(c("$1,000","$900","$100"), ncol = 3,\r
358                 dimnames = list("$\\alpha$",\r
359                                 c("Income (US$)","Expenses (US$)",\r
360                                   "Profit (US$)")))\r
361 print(xtable(money), sanitize.rownames.function = function(x) {x})\r
362 @\r
363 \r
364 \section{Format examples}\r
365 \subsection{Adding a centering environment}\r
366 <<results='asis'>>=\r
367 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"\""),\r
368       floating = TRUE, latex.environments = "")\r
369 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"center\""),\r
370       floating = TRUE, latex.environments = "center")\r
371 @\r
372 \r
373 \newpage\r
374 \r
375 \subsection{Column alignment}\r
376 <<results='asis'>>=\r
377 tli.table <- xtable(tli[1:10, ])\r
378 align(tli.table) <- rep("r", 6)\r
379 tli.table\r
380 @\r
381 \r
382 \subsubsection{Left aligned strings with column lines}\r
383 <<results='asis'>>=\r
384 align(tli.table) <- "|rrl|l|lr|"\r
385 tli.table\r
386 @\r
387 \r
388 \subsubsection{Fixed width columns}\r
389 <<results='asis'>>=\r
390 align(tli.table) <- "|rr|lp{3cm}l|r|"\r
391 tli.table\r
392 @\r
393 \r
394 \newpage\r
395 \r
396 \subsection{Number of digits}\r
397 One number for all columns,\r
398 <<results='asis'>>=\r
399 display(tli.table)[c(2,6)] <- "f"\r
400 digits(tli.table) <- 3\r
401 tli.table\r
402 @\r
403 \r
404 \p\r
405 or one for each column, including the row names,\r
406 <<results='asis'>>=\r
407 digits(tli.table) <- 1:(ncol(tli)+1)\r
408 tli.table\r
409 @\r
410 \r
411 \p\r
412 or as a full matrix.\r
413 <<results='asis'>>=\r
414 digits(tli.table) <- matrix(0:4, nrow = 10, ncol = ncol(tli)+1)\r
415 tli.table\r
416 @\r
417 \r
418 \newpage\r
419 \r
420 \subsection{Suppress row/column names}\r
421 \subsubsection{Suppress row names}\r
422 <<results='asis'>>=\r
423 tli.table <- xtable(tli[1:10, ])\r
424 print(tli.table, include.rownames = FALSE)\r
425 @\r
426 \r
427 \p\r
428 If you want a vertical line on the left, you need to change the \code{align}\r
429 attribute.\r
430 <<results='asis'>>=\r
431 align(tli.table) <- "|r|r|lp{3cm}l|r|"\r
432 print(tli.table, include.rownames = FALSE)\r
433 @\r
434 \r
435 \p\r
436 Revert the alignment to what is was before.\r
437 <<>>=\r
438 align(tli.table) <- "|rr|lp{3cm}l|r|"\r
439 @\r
440 \r
441 \newpage\r
442 \r
443 \subsubsection{Suppress column names}\r
444 <<results='asis'>>=\r
445 print(tli.table, include.colnames = FALSE)\r
446 @\r
447 \r
448 \p\r
449 Note the doubled header lines which can be suppressed.\r
450 <<results='asis'>>=\r
451 print(tli.table, include.colnames = FALSE,\r
452       hline.after = c(0,nrow(tli.table)))\r
453 @\r
454 \r
455 \subsubsection{Suppress row and column names}\r
456 <<results='asis'>>=\r
457 print(tli.table, include.colnames = FALSE, include.rownames = FALSE)\r
458 @\r
459 \r
460 \newpage\r
461 \r
462 \subsection{Rotate row/column names}\r
463 The \code{rotate.rownames} and \code{rotate.colnames} arguments can be\r
464 used to rotate the row and/or column names. This requires\r
465 \verb|\usepackage{rotating}| in the \LaTeX\ preamble.\r
466 \r
467 <<results='asis'>>=\r
468 print(tli.table, rotate.rownames = TRUE, rotate.colnames = TRUE)\r
469 @\r
470 \r
471 \newpage\r
472 \r
473 \subsection{Horizontal lines}\r
474 \subsubsection{Line locations}\r
475 Use the \code{hline.after} argument to specify the position of the\r
476 horizontal lines.\r
477 \r
478 <<results='asis'>>=\r
479 print(xtable(anova(fm3)), hline.after = c(1))\r
480 @\r
481 \r
482 \subsubsection{Line styles}\r
483 Specifying \code{booktabs = TRUE} will generate three line types. By\r
484 default, when no value is given for \code{hline.after}, a\r
485 \verb|\toprule| will be drawn above the table, a \verb|\midrule| after\r
486 the table headings and a \verb|\bottomrule| below the table. This\r
487 requires \verb|\usepackage{booktabs}| in the \LaTeX\ preamble.\r
488 \r
489 \p\r
490 \r
491 The top and bottom rules are slightly thicker than the mid rule. The\r
492 thickness of the lines can be set via the \LaTeX\ lengths\r
493 \verb|\heavyrulewidth| and \verb|\lightrulewidth|.\r
494 \r
495 <<results='asis'>>=\r
496 tli.table <- xtable(tli[1:10, ])\r
497 print(tli.table, include.rownames = FALSE, booktabs = TRUE)\r
498 @\r
499 \r
500 \p\r
501 \r
502 If \code{hline.after} includes \code{-1}, a \verb|\toprule| will be\r
503 drawn above the table. If \code{hline.after} includes the number of\r
504 rows in the table, a \verb|\bottomrule| will be drawn below the\r
505 table. For any other values specified in \code{hline.after}, a\r
506 \verb|\midrule| will be drawn after that line of the table.\r
507 \r
508 \p\r
509 The following table has more than one \verb|\midrule|.\r
510 \r
511 <<results='asis'>>=\r
512 bktbs <- xtable(matrix(1:10, ncol = 2))\r
513 hlines <- c(-1, 0, 1, nrow(bktbs))\r
514 print(bktbs, booktabs = TRUE, hline.after = hlines)\r
515 @\r
516 \r
517 \subsection{Table level commands}\r
518 <<results='asis'>>=\r
519 print(xtable(anova(fm3)), size = "large")\r
520 @\r
521 \r
522 \p\r
523 <<results='asis'>>=\r
524 print(xtable(anova(fm3)), size = "\\setlength{\\tabcolsep}{12pt}")\r
525 @\r
526 \r
527 \subsection{Long tables}\r
528 Requires \verb|\usepackage{longtable}| in the \LaTeX\ preamble.\r
529 \r
530 <<results='asis'>>=\r
531 x <- matrix(rnorm(1000), ncol = 10)\r
532 x.big <- xtable(x, caption = "A \\code{longtable} spanning several pages")\r
533 print(x.big, hline.after=c(-1, 0), tabular.environment = "longtable")\r
534 @\r
535 \r
536 Extra features of the \pkg{longtable} \LaTeX{} package can typically\r
537 be activated using \code{add.to.row}, as shown below.\r
538 \r
539 <<results='asis'>>=\r
540 add.to.row <- list(pos = list(0), command = NULL)\r
541 command <- paste0("\\hline\n\\endhead\n",\r
542                   "\\hline\n",\r
543                   "\\multicolumn{", dim(x)[2] + 1, "}{l}",\r
544                   "{\\footnotesize Continued on next page}\n",\r
545                   "\\endfoot\n",\r
546                   "\\endlastfoot\n")\r
547 add.to.row$command <- command\r
548 print(x.big, hline.after=c(-1), add.to.row = add.to.row,\r
549       tabular.environment = "longtable")\r
550 @\r
551 \r
552 \r
553 \newpage\r
554 \r
555 \subsection{Use of \code{add.to.row} argument}\r
556 The following frequency table has outer dimnames: \code{Grade3} and\r
557 \code{Grade6}.\r
558 \r
559 <<>>=\r
560 Grade3 <- c("A","B","B","A","B","C","C","D","A","B",\r
561             "C","C","C","D","B","B","D","C","C","D")\r
562 Grade6 <- c("A","A","A","B","B","B","B","B","C","C",\r
563             "A","C","C","C","D","D","D","D","D","D")\r
564 Cohort <- table(Grade3, Grade6)\r
565 Cohort\r
566 @\r
567 \r
568 \p\r
569 The default behavior of \code{print.xtable} is to strip outer dimnames.\r
570 <<results='asis'>>=\r
571 xtable(Cohort)\r
572 @\r
573 \r
574 \p\r
575 The desired column labels can be created using \code{add.to.row}, in this case\r
576 applying two commands to ``row number zero'' while suppressing the basic column\r
577 names.\r
578 \r
579 <<results='asis'>>=\r
580 addtorow <- list()\r
581 addtorow$pos <- list(0, 0)\r
582 addtorow$command <- c("& \\multicolumn{4}{c}{Grade 6} \\\\\n",\r
583                       "Grade 3 & A & B & C & D \\\\\n")\r
584 print(xtable(Cohort), add.to.row = addtorow, include.colnames = FALSE)\r
585 @\r
586 \r
587 \subsection{Sideways tables}\r
588 Requires \verb|\usepackage{rotating}| in the LaTeX\r
589 preamble.  Sideways tables can't be forced in place with the \code{[H]}\r
590 specifier, but you can use the \verb|\clearpage| command to get them\r
591 fairly nearby.\r
592 \r
593 <<results='asis'>>=\r
594 x <- x[1:30, ]\r
595 x.side <- xtable(x, caption = "A sideways table")\r
596 print(x.side, floating = TRUE, floating.environment = "sidewaystable")\r
597 @\r
598 \clearpage\r
599 \r
600 \subsection{Rescaled tables}\r
601 Specify a \code{scalebox} value to rescale the table.\r
602 <<results='asis'>>=\r
603 x <- x[1:20, ]\r
604 x.rescale <- xtable(x)\r
605 print(x.rescale, scalebox = 0.7)\r
606 @\r
607 \r
608 \subsection{Aligning fixed width columns}\r
609 Note that using specifications such as \verb|p{2cm}| always\r
610 produces a \textbf{left aligned} column. What if some other alignment\r
611 is desired?\r
612 \r
613 This is not really a problem with \pkg{xtable} but with the formatting\r
614 of tables with fixed width columns and different alignments using\r
615 standard \LaTeX.\r
616 \r
617 One solution is to use the \verb|array| package, defining new\r
618 column formats.\r
619 \r
620 \begin{verbatim}\r
621 \newcolumntype{L}[1]{>{\raggedright\let\newline\\\r
622     \arraybackslash\hspace{0pt}}m{#1}}\r
623 \newcolumntype{C}[1]{>{\centering\let\newline\\\r
624     \arraybackslash\hspace{0pt}}m{#1}}\r
625 \newcolumntype{R}[1]{>{\raggedleft\let\newline\\\r
626     \arraybackslash\hspace{0pt}}m{#1}}\r
627 \newcolumntype{P}[1]{>{\raggedright\tabularxbackslash}p{#1}}\r
628 \end{verbatim}\r
629 \r
630 These allow for very sophisticated cell formatting, namely\r
631 left-aligned, centred, or right-aligned text, with recognition of line\r
632 breaks for the first three new column types. If these lines are\r
633 included along with \verb|\usepackage{array}|, then the following is\r
634 possible.\r
635 \r
636 \newcolumntype{L}[1]{>{\raggedright\let\newline\\\r
637     \arraybackslash\hspace{0pt}}m{#1}}\r
638 \newcolumntype{C}[1]{>{\centering\let\newline\\\r
639     \arraybackslash\hspace{0pt}}m{#1}}\r
640 \newcolumntype{R}[1]{>{\raggedleft\let\newline\\\r
641     \arraybackslash\hspace{0pt}}m{#1}}\r
642 \newcolumntype{P}[1]{>{\raggedright\tabularxbackslash}p{#1}}\r
643 \r
644 <<results='asis'>>=\r
645 df <- data.frame(name = c("A","B"), right = c(1.4, 34.6),\r
646                  left = c(1.4, 34.6), text = c("txt1","txt2"))\r
647 print(xtable(df, align = c("l", "|c", "|R{3cm}", "|L{3cm}", "| p{3cm}|")),\r
648       floating = FALSE, include.rownames = FALSE)\r
649 @\r
650 \r
651 \newpage\r
652 \r
653 \subsection{Table width}\r
654 The \code{tabularx} environment is for typesetting tables whose\r
655 overall width is fixed. The column alignment code \code{X} denotes\r
656 columns that will be stretched to achieve the desired table\r
657 width. Requires \verb|\usepackage{tabularx}| in the \LaTeX\ preamble.\r
658 \r
659 <<results='asis'>>=\r
660 df.width <- data.frame(One = c("item 1", "A"), Two = c("item 2", "B"),\r
661                        Three = c("item 3", "C"), Four = c("item 4", "D"))\r
662 x.width <- xtable(df.width)\r
663 align(x.width) <- "|l|X|l|l|l|"\r
664 print(x.width, tabular.environment = "tabularx", width = "\\textwidth")\r
665 @\r
666 \r
667 \section{Suppressing printing}\r
668 By default the \code{print} method will print the \LaTeX\ or HTML to\r
669 standard output and also return the character strings invisibly.  The\r
670 printing to standard output can be suppressed by specifying\r
671 \code{print.results = FALSE}.\r
672 \r
673 <<>>=\r
674 x.out <- print(tli.table, print.results = FALSE)\r
675 @\r
676 \r
677 Formatted output can also be captured without printing with the\r
678 \code{toLatex} method.  This function returns an object of class\r
679 \code{"Latex"}.\r
680 \r
681 <<>>=\r
682 x.ltx <- toLatex(tli.table)\r
683 class(x.ltx)\r
684 x.ltx\r
685 @\r
686 \r
687 \r
688 \newpage\r
689 \r
690 \section{Acknowledgements}\r
691 Most of the examples in this gallery are taken from the \pkg{xtable}\r
692 documentation. Two examples (\code{add.to.row} and `Aligning fixed width\r
693 columns') are from Stack Exchange.\r
694 \r
695 \section{Session information}\r
696 <<results='asis'>>=\r
697 toLatex(sessionInfo())\r
698 @\r
699 \r
700 \end{document}\r