]> git.donarmstrong.com Git - xtable.git/blob - pkg/vignettes/xtableGallery.Rnw
b2132a787774f3c9cf7629445c914b6234942f8d
[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}\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
16 \usepackage{tabularx}\r
17 \newcommand\code[1]{\texttt{#1}}\r
18 \newcommand\p{\vspace{2ex}}\r
19 \setcounter{tocdepth}{2}\r
20 \begin{document}\r
21 \r
22 \title{The xtable Gallery}\r
23 \author{Jonathan Swinton and others}\r
24 \maketitle\r
25 \r
26 \tableofcontents\r
27 \r
28 \newpage\r
29 \r
30 <<include=FALSE>>=\r
31 library(knitr)\r
32 opts_chunk$set(fig.path='figdir/fig', debug=TRUE, echo=TRUE)\r
33 @\r
34 \r
35 \section{Gallery}\r
36 \subsection{Data frame}\r
37 <<results='asis'>>=\r
38 library(xtable)\r
39 options(xtable.floating = FALSE)\r
40 data(tli)\r
41 xtable(tli[1:10, ])\r
42 @\r
43 \r
44 \subsection{Matrix}\r
45 <<results='asis'>>=\r
46 design.matrix <- model.matrix(~ sex*grade, data = tli[1:10, ])\r
47 xtable(design.matrix, digits = 0)\r
48 @\r
49 \r
50 \subsection{aov}\r
51 <<results='asis'>>=\r
52 fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)\r
53 xtable(fm1)\r
54 @\r
55 \r
56 \newpage\r
57 \r
58 \subsection{lm}\r
59 <<results='asis'>>=\r
60 fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)\r
61 xtable(fm2)\r
62 @\r
63 \r
64 \subsubsection{Anova table (one model)}\r
65 <<results='asis'>>=\r
66 xtable(anova(fm2))\r
67 @\r
68 \r
69 \subsubsection{Anova table (two models)}\r
70 <<results='asis'>>=\r
71 fm2b <- lm(tlimth ~ ethnicty, data = tli)\r
72 xtable(anova(fm2b, fm2))\r
73 @\r
74 \r
75 \subsection{glm}\r
76 <<results='asis'>>=\r
77 fm3 <- glm(disadvg ~ ethnicty*grade, data = tli, family = binomial)\r
78 xtable(fm3)\r
79 @\r
80 \r
81 \p\r
82 <<results='asis'>>=\r
83 xtable(anova(fm3))\r
84 @\r
85 \r
86 \subsection{prcomp}\r
87 <<results='asis'>>=\r
88 pr1 <- prcomp(USArrests)\r
89 xtable(pr1)\r
90 @\r
91 \r
92 \p\r
93 <<results='asis'>>=\r
94 xtable(summary(pr1))\r
95 @\r
96 \r
97 <<include=FALSE>>=\r
98 # pr2 <- princomp(USArrests)\r
99 # xtable(pr2)\r
100 @\r
101 \r
102 \subsection{Time series}\r
103 <<results='asis'>>=\r
104 temp.ts <- ts(cumsum(1 + round(rnorm(100), 0)),\r
105               start = c(1954, 7), frequency = 12)\r
106 temp.table <- xtable(temp.ts, digits = 0)\r
107 temp.table\r
108 @\r
109 \r
110 <<include=FALSE>>=\r
111 # ## Demonstrate saving to file\r
112 # for(i in c("latex", "html")) {\r
113 #   outFileName <- paste("xtable.", ifelse(i=="latex", "tex", i), sep = "")\r
114 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
115 #         latex.environments = NULL)\r
116 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
117 #         latex.environments = "")\r
118 #   print(xtable(lm.D9), type = i, file = outFileName, append = TRUE,\r
119 #         latex.environments = "center")\r
120 #   print(xtable(anova(glm.D93, test = "Chisq")),\r
121 #         type = i, file = outFileName,\r
122 #         append = TRUE)\r
123 #   print(xtable(anova(glm.D93)), hline.after = c(1),\r
124 #         size = "small", type = i,\r
125 #         file = outFileName, append = TRUE)\r
126 #   # print(xtable(pr2), type = i, file = outFileName, append = TRUE)\r
127 # }\r
128 @\r
129 \r
130 \newpage\r
131 \r
132 \section{Helper functions for formatting}\r
133 The functions \code{xalign}, \code{xdigits}, and \code{xdisplay} are useful for\r
134 formatting tables in a sensible way. Consider the output produced by the default\r
135 formatting.\r
136 \r
137 <<results='asis'>>=\r
138 dat <- mtcars[1:3, 1:6]\r
139 x <- xtable(dat)\r
140 x\r
141 @\r
142 \r
143 \p\r
144 Now change the default alignment, digits and display using helper functions\r
145 \code{xalign}, \code{xdigits}, and \code{xdisplay}. This produces a better\r
146 format as shown below.\r
147 \r
148 <<results='asis'>>=\r
149 align(x) <- xalign(x)\r
150 digits(x) <- xdigits(x)\r
151 display(x) <- xdisplay(x)\r
152 x\r
153 @\r
154 \r
155 \newpage\r
156 \r
157 \section{Sanitization}\r
158 <<results='asis'>>=\r
159 insane <- data.frame(Name = c("Ampersand","Greater than","Less than",\r
160                             "Underscore","Per cent","Dollar",\r
161                             "Backslash","Hash","Caret","Tilde",\r
162                             "Left brace","Right brace"),\r
163                      Character = I(c("&",">","<","_","%","$",\r
164                                      "\\","#","^","~","{","}")))\r
165 colnames(insane)[2] <- paste(insane[, 2], collapse = "")\r
166 xtable(insane)\r
167 @\r
168 \r
169 \p\r
170 Sometimes you might want to have your own sanitization function.\r
171 \r
172 <<results='asis'>>=\r
173 wanttex <- xtable(data.frame(Column =\r
174                              paste("Value_is $10^{-",1:3,"}$", sep = "")))\r
175 print(wanttex, sanitize.text.function =\r
176       function(str) gsub("_", "\\_", str, fixed = TRUE))\r
177 @\r
178 \r
179 \newpage\r
180 \r
181 \subsection{Markup in tables}\r
182 Markup can be included in tables, including in column and row names, by using\r
183 a custom \code{sanitize.text.function}.\r
184 \r
185 <<results='asis'>>=\r
186 mat <- round(matrix(c(0.9, 0.89, 200, 0.045, 2.0), c(1, 5)), 4)\r
187 rownames(mat) <- "$y_{t-1}$"\r
188 colnames(mat) <- c("$R^2$", "$\\bar{x}$", "F-stat", "S.E.E", "DW")\r
189 mat <- xtable(mat)\r
190 print(mat, sanitize.text.function = function(x) {x})\r
191 @\r
192 \r
193 % By David Dahl to demonstrate contribution from David Whitting, 2007-10-09.\r
194 \p\r
195 You can also have sanitize functions that are specific to column or\r
196 row names.  In the table below, the row name is not sanitized but\r
197 column names and table elements are.\r
198 \r
199 <<results='asis'>>=\r
200 money <- matrix(c("$1,000","$900","$100"), ncol = 3,\r
201                 dimnames = list("$\\alpha$",\r
202                                 c("Income (US$)","Expenses (US$)",\r
203                                   "Profit (US$)")))\r
204 print(xtable(money), sanitize.rownames.function = function(x) {x})\r
205 @\r
206 \r
207 \section{Format examples}\r
208 \subsection{Adding a centering environment}\r
209 <<results='asis'>>=\r
210 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"\""),\r
211       floating = TRUE, latex.environments = "")\r
212 print(xtable(anova(fm3), caption = "\\tt latex.environments = \"center\""),\r
213       floating = TRUE, latex.environments = "center")\r
214 @\r
215 \r
216 \newpage\r
217 \r
218 \subsection{Column alignment}\r
219 <<results='asis'>>=\r
220 tli.table <- xtable(tli[1:10, ])\r
221 align(tli.table) <- rep("r", 6)\r
222 tli.table\r
223 @\r
224 \r
225 \subsubsection{Left aligned strings with column lines}\r
226 <<results='asis'>>=\r
227 align(tli.table) <- "|rrl|l|lr|"\r
228 tli.table\r
229 @\r
230 \r
231 \subsubsection{Fixed width columns}\r
232 <<results='asis'>>=\r
233 align(tli.table) <- "|rr|lp{3cm}l|r|"\r
234 tli.table\r
235 @\r
236 \r
237 \newpage\r
238 \r
239 \subsection{Number of digits}\r
240 One number for all columns,\r
241 <<results='asis'>>=\r
242 display(tli.table)[c(2,6)] <- "f"\r
243 digits(tli.table) <- 3\r
244 tli.table\r
245 @\r
246 \r
247 \p\r
248 or one for each column, including the row names,\r
249 <<results='asis'>>=\r
250 digits(tli.table) <- 1:(ncol(tli)+1)\r
251 tli.table\r
252 @\r
253 \r
254 \p\r
255 or as a full matrix.\r
256 <<results='asis'>>=\r
257 digits(tli.table) <- matrix(0:4, nrow = 10, ncol = ncol(tli)+1)\r
258 tli.table\r
259 @\r
260 \r
261 \newpage\r
262 \r
263 \subsection{Suppress row/column names}\r
264 \subsubsection{Suppress row names}\r
265 <<results='asis'>>=\r
266 tli.table <- xtable(tli[1:10, ])\r
267 print(tli.table, include.rownames = FALSE)\r
268 @\r
269 \r
270 \p\r
271 If you want a vertical line on the left, you need to change the \code{align}\r
272 attribute.\r
273 <<results='asis'>>=\r
274 align(tli.table) <- "|r|r|lp{3cm}l|r|"\r
275 print(tli.table, include.rownames = FALSE)\r
276 @\r
277 \r
278 \p\r
279 Revert the alignment to what is was before.\r
280 <<>>=\r
281 align(tli.table) <- "|rr|lp{3cm}l|r|"\r
282 @\r
283 \r
284 \newpage\r
285 \r
286 \subsubsection{Suppress column names}\r
287 <<results='asis'>>=\r
288 print(tli.table, include.colnames = FALSE)\r
289 @\r
290 \r
291 \p\r
292 Note the doubled header lines which can be suppressed.\r
293 <<results='asis'>>=\r
294 print(tli.table, include.colnames = FALSE,\r
295       hline.after = c(0,nrow(tli.table)))\r
296 @\r
297 \r
298 \subsubsection{Suppress row and column names}\r
299 <<results='asis'>>=\r
300 print(tli.table, include.colnames = FALSE, include.rownames = FALSE)\r
301 @\r
302 \r
303 \newpage\r
304 \r
305 \subsection{Rotate row/column names}\r
306 The \code{rotate.rownames} and \code{rotate.colnames} arguments can be used to\r
307 rotate the row and/or column names. This requires \verb|\usepackage{rotating}|\r
308 in the \LaTeX\ preamble.\r
309 \r
310 <<results='asis'>>=\r
311 print(tli.table, rotate.rownames = TRUE, rotate.colnames = TRUE)\r
312 @\r
313 \r
314 \newpage\r
315 \r
316 \subsection{Horizontal lines}\r
317 \subsubsection{Line locations}\r
318 Use the \code{hline.after} argument to specify the position of the\r
319 horizontal lines.\r
320 \r
321 <<results='asis'>>=\r
322 print(xtable(anova(fm3)), hline.after = c(1))\r
323 @\r
324 \r
325 \subsubsection{Line styles}\r
326 Specifying \code{booktabs = TRUE} will generate three line types. By default,\r
327 when no value is given for \code{hline.after}, a \verb|\toprule| will be drawn\r
328 above the table, a \verb|\midrule| after the table headings and a\r
329 \verb|\bottomrule| below the table. This requires \verb|\usepackage{booktabs}|\r
330 in the \LaTeX\ preamble.\r
331 \r
332 \p\r
333 The top and bottom rules are slightly thicker than the mid rule. The thickness\r
334 of the lines can be set via the \LaTeX\ lengths \verb|\heavyrulewidth| and\r
335 \verb|\lightrulewidth|.\r
336 \r
337 <<results='asis'>>=\r
338 tli.table <- xtable(tli[1:10, ])\r
339 print(tli.table, include.rownames = FALSE, booktabs = TRUE)\r
340 @\r
341 \r
342 \p\r
343 If \code{hline.after} includes \code{-1}, a \verb|\toprule| will be\r
344 drawn above the table. If \code{hline.after} includes the number of\r
345 rows in the table, a \verb|\bottomrule| will be drawn below the\r
346 table. For any other values specified in \code{hline.after}, a\r
347 \verb|\midrule| will be drawn after that line of the table.\r
348 \r
349 \p\r
350 The following table has more than one \verb|\midrule|.\r
351 \r
352 <<results='asis'>>=\r
353 bktbs <- xtable(matrix(1:10, ncol = 2))\r
354 hlines <- c(-1, 0, 1, nrow(bktbs))\r
355 print(bktbs, booktabs = TRUE, hline.after = hlines)\r
356 @\r
357 \r
358 \subsection{Table level commands}\r
359 <<results='asis'>>=\r
360 print(xtable(anova(fm3)), size = "large")\r
361 @\r
362 \r
363 \p\r
364 <<results='asis'>>=\r
365 print(xtable(anova(fm3)), size = "\\setlength{\\tabcolsep}{12pt}")\r
366 @\r
367 \r
368 \subsection{Long tables}\r
369 Requires \verb|\usepackage{longtable}| in the \LaTeX\ preamble.\r
370 \r
371 <<results='asis'>>=\r
372 x <- matrix(rnorm(1000), ncol = 10)\r
373 x.big <- xtable(x, caption = 'A \\code{longtable} spanning several pages')\r
374 print(x.big, hline.after=c(-1, 0), tabular.environment = 'longtable')\r
375 @\r
376 \r
377 %% The column name alignment is off in the following example.\r
378 %% It needs some revision before exposing it. - CR, 7/2/2012\r
379 %\r
380 %\subsubsection{Long tables with the header on each page}\r
381 %The \code{add.to.row} argument can be used to display the header\r
382 %for a long table on each page, and to add a "continued" footer\r
383 %on all pages except the last page.\r
384 %\r
385 %<<results=tex>>=\r
386 %library(xtable)\r
387 %x<-matrix(rnorm(1000), ncol = 10)\r
388 %addtorow<-list()\r
389 %addtorow$pos<-list()\r
390 %addtorow$pos[[1]]<-c(0)\r
391 %addtorow$command<-c(paste(\r
392 %    "\\hline \n",\r
393 %    "  \\endhead \n",\r
394 %    "  \\hline \n",\r
395 %    "  {\\footnotesize Continued on next page} \n",\r
396 %    "  \\endfoot \n",\r
397 %    "  \\endlastfoot \n", sep = ""))\r
398 %x.big2 <- xtable(x, label = "tabbig2",\r
399 %    caption = "Example of longtable with the header on each page")\r
400 %print(x.big2, tabular.environment = "longtable",\r
401 %include.rownames = FALSE, add.to.row = addtorow, hline.after = c(-1))\r
402 %@\r
403 \r
404 \subsection{Sideways tables}\r
405 Requires \verb|\usepackage{rotating}| in the LaTeX\r
406 preamble.  Sideways tables can't be forced in place with the \code{[H]}\r
407 specifier, but you can use the \verb|\clearpage| command to get them\r
408 fairly nearby.\r
409 \r
410 <<results='asis'>>=\r
411 x <- x[1:30, ]\r
412 x.side <- xtable(x, caption = 'A sideways table')\r
413 print(x.side, floating = TRUE, floating.environment = 'sidewaystable')\r
414 @\r
415 \clearpage\r
416 \r
417 \subsection{Rescaled tables}\r
418 Specify a \code{scalebox} value to rescale the table.\r
419 <<results='asis'>>=\r
420 x <- x[1:20, ]\r
421 x.rescale <- xtable(x)\r
422 print(x.rescale, scalebox = 0.7)\r
423 @\r
424 \r
425 \subsection{Table width}\r
426 The \code{tabularx} environment is for typesetting tables whose overall width is\r
427 fixed. The column alignment code \code{X} denotes columns that will be stretched\r
428 to achieve the desired table width. Requires \verb|\usepackage{tabularx}| in the\r
429 \LaTeX\ preamble.\r
430 \r
431 <<results='asis'>>=\r
432 df.width <- data.frame(One = c("item 1", "A"), Two = c("item 2", "B"),\r
433                        Three = c("item 3", "C"), Four = c("item 4", "D"))\r
434 x.width <- xtable(df.width)\r
435 align(x.width) <- "|l|X|l|l|l|"\r
436 print(x.width, tabular.environment = "tabularx", width = "\\textwidth")\r
437 @\r
438 \r
439 \newpage\r
440 \r
441 \section{Suppressing printing}\r
442 By default the \code{print} method will print the \LaTeX\ or HTML to standard\r
443 output and also return the character strings invisibly.  The printing to\r
444 standard output can be suppressed by specifying \code{print.results = FALSE}.\r
445 \r
446 <<>>=\r
447 x.out <- print(tli.table, print.results = FALSE)\r
448 @\r
449 \r
450 Formatted output can also be captured without printing with the\r
451 \code{toLatex} method.  This function returns an object of class\r
452 \code{"Latex"}.\r
453 \r
454 <<>>=\r
455 x.ltx <- toLatex(tli.table)\r
456 class(x.ltx)\r
457 x.ltx\r
458 @\r
459 \r
460 \section{Acknowledgements}\r
461 Most of the examples in this gallery are taken from the \code{xtable}\r
462 documentation.\r
463 \r
464 \section{R session information}\r
465 <<results='asis'>>=\r
466 toLatex(sessionInfo())\r
467 @\r
468 \r
469 \end{document}\r