]> git.donarmstrong.com Git - xtable.git/blob - pkg/inst/doc/xtableGallery.snw
Added the "width" argument for use with "tabular*" or "tabularx" tabular environments.
[xtable.git] / pkg / inst / doc / xtableGallery.snw
1 %\VignetteIndexEntry{xtable Gallery}
2 %\VignetteDepends{xtable}
3 %\VignetteKeywords{LaTeX,HTML,table}
4 %\VignettePackage{xtable}
5
6 %**************************************************************************
7 %
8 % # $Id:$
9
10 % $Revision:  $
11 % $Author: $
12 % $Date:  $
13
14 <<echo=FALSE,eval=FALSE>>=
15 makeme <- function() {
16         # I am a convenience function for debugging and can be ignored
17         setwd("C:/JonathanSwinton/PathwayModeling/src/R/SourcePackages/xtable/inst/doc")
18         Sweave("xtableGallery.RnW",stylepath=FALSE)
19 }
20 makeme()
21 @
22
23 \documentclass[letterpaper]{article}
24
25 \title{
26 The xtable gallery
27 }
28 \author{Jonathan Swinton <jonathan@swintons.net>\\ with small contributions from others}
29
30 \usepackage{Sweave}
31 \SweaveOpts{prefix.string=figdir/fig,debug=TRUE,eps=FALSE,echo=TRUE}
32 \usepackage{rotating} 
33 \usepackage{longtable} 
34 \usepackage{booktabs}
35 \usepackage{tabularx}
36 %\usepackage{hyperref}
37 \begin{document}
38
39 \maketitle
40 \section{Summary}
41 This document gives a gallery of tables which can be made 
42 by using the {\tt xtable} package to create \LaTeX\ output.
43 It doubles as a regression check for the package.
44
45 <<>>=
46 library(xtable)
47 @
48
49 \section{Gallery}
50 \subsection{Data frame}
51 Load example dataset
52 <<>>=
53 data(tli)
54
55 ## Demonstrate data.frame
56 tli.table <- xtable(tli[1:10,])
57 digits(tli.table)[c(2,6)] <- 0
58 @
59 <<results=tex>>=
60 print(tli.table,floating=FALSE)
61 @
62
63 \subsection{Matrix}
64 <<>>=
65 design.matrix <- model.matrix(~ sex*grade, data=tli[1:10,])
66 design.table <- xtable(design.matrix)
67 @
68 <<results=tex>>=
69 print(design.table,floating=FALSE)
70 @
71
72 \subsection{aov}
73 <<>>=
74 fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data=tli)
75 fm1.table <- xtable(fm1)
76 @
77 <<results=tex>>=
78 print(fm1.table,floating=FALSE)
79 @
80 \subsection{lm}
81 <<>>=
82 fm2 <- lm(tlimth ~ sex*ethnicty, data=tli)
83 fm2.table <- xtable(fm2)
84 @
85 <<results=tex>>=
86 print(fm2.table,floating=FALSE)
87 @
88 \subsubsection{anova object}
89
90 <<results=tex>>=
91 print(xtable(anova(fm2)),floating=FALSE)
92 @
93 \subsubsection{Another anova object}
94 <<>>=
95 fm2b <- lm(tlimth ~ ethnicty, data=tli)
96 @
97 <<results=tex>>=
98 print(xtable(anova(fm2b,fm2)),floating=FALSE)
99 @
100
101
102 \subsection{glm}
103
104 <<>>=
105
106 ## Demonstrate glm
107 fm3 <- glm(disadvg ~ ethnicty*grade, data=tli, family=binomial())
108 fm3.table <- xtable(fm3)
109 @
110 <<results=tex>>=
111 print(fm3.table,floating=FALSE)
112 @
113
114 \subsubsection{anova object}
115 @
116 <<results=tex>>=
117 print(xtable(anova(fm3)),floating=FALSE)
118 @
119
120
121 \subsection{More aov}
122 <<>>=
123
124 ## Demonstrate aov
125 ## Taken from help(aov) in R 1.1.1
126 ## From Venables and Ripley (1997) p.210.
127 N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
128 P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
129 K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
130 yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,55.0,
131            62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)
132 npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P), K=factor(K), yield=yield)
133 npk.aov <- aov(yield ~ block + N*P*K, npk)
134 op <- options(contrasts=c("contr.helmert", "contr.treatment"))
135 npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
136 options(op)
137 #summary(npk.aov)
138 @
139 <<results=tex>>=
140 print(xtable(npk.aov),floating=FALSE)
141 @
142
143 \subsubsection{anova object}
144 <<results=tex>>=
145 print(xtable(anova(npk.aov)),floating=FALSE)
146 @
147
148 \subsubsection{Another anova object}
149 <<results=tex>>=
150 print(xtable(summary(npk.aov)),floating=FALSE)
151 @
152
153 <<>>=
154 #summary(npk.aovE)
155 @
156 <<results=tex>>=
157 print(xtable(npk.aovE),floating=FALSE)
158 @
159
160
161 <<results=tex>>=
162 print(xtable(summary(npk.aovE)),floating=FALSE)
163 @
164
165 \subsection{More lm}
166 <<>>=
167
168 ## Demonstrate lm
169 ## Taken from help(lm) in R 1.1.1
170 ## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
171 ## Page 9: Plant Weight Data.
172 ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
173 trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
174 group <- gl(2,10,20, labels=c("Ctl","Trt"))
175 weight <- c(ctl, trt)
176 lm.D9 <- lm(weight ~ group)
177 @
178 <<results=tex>>=
179 print(xtable(lm.D9),floating=FALSE)
180 @
181
182
183 <<results=tex>>=
184 print(xtable(anova(lm.D9)),floating=FALSE)
185 @
186
187 \subsection{More glm}
188 <<>>=
189
190 ## Demonstrate glm
191 ## Taken from help(glm) in R 1.1.1
192 ## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
193 ## Page 93: Randomized Controlled Trial :
194 counts <- c(18,17,15,20,10,20,25,13,12)
195 outcome <- gl(3,1,9)
196 treatment <- gl(3,3)
197 d.AD <- data.frame(treatment, outcome, counts)
198 glm.D93 <- glm(counts ~ outcome + treatment, family=poisson())
199 @
200 <<results=tex>>=
201 print(xtable(glm.D93,align="r|llrc"),floating=FALSE)
202 @
203
204 \subsection{prcomp}
205 <<prcomp>>=
206 if(require(stats,quietly=TRUE)) {
207   ## Demonstrate prcomp
208   ## Taken from help(prcomp) in mva package of R 1.1.1
209   data(USArrests)
210   pr1 <- prcomp(USArrests)
211 }
212 @
213 <<results=tex>>=
214 if(require(stats,quietly=TRUE)) {
215   print(xtable(pr1),floating=FALSE)
216 }
217 @
218
219
220 @
221 <<results=tex>>=
222   print(xtable(summary(pr1)),floating=FALSE)
223 @
224
225
226
227 <<>>=
228 #  ## Demonstrate princomp
229 #  ## Taken from help(princomp) in mva package of R 1.1.1
230 #  pr2 <- princomp(USArrests)
231 #  print(xtable(pr2))
232 @
233 \subsection{Time series}
234
235 <<>>=
236 temp.ts <- ts(cumsum(1+round(rnorm(100), 0)), start = c(1954, 7), frequency=12)
237    temp.table <- xtable(temp.ts,digits=0)
238     caption(temp.table) <- "Time series example"
239 @
240 <<results=tex>>=
241     print(temp.table,floating=FALSE)
242 @
243 <<savetofile,echo=FALSE>>=
244 if (FALSE) {
245   for(i in c("latex","html")) {
246     outFileName <- paste("xtable.",ifelse(i=="latex","tex",i),sep="")
247     print(xtable(lm.D9),type=i,file=outFileName,append=TRUE,latex.environment=NULL)
248     print(xtable(lm.D9),type=i,file=outFileName,append=TRUE,latex.environment="")
249     print(xtable(lm.D9),type=i,file=outFileName,append=TRUE,latex.environment="center")
250     print(xtable(anova(glm.D93,test="Chisq")),type=i,file=outFileName,append=TRUE)
251     print(xtable(anova(glm.D93)),hline.after=c(1),size="small",type=i,file=outFileName,append=TRUE)
252       # print(xtable(pr2),type=i,file=outFileName,append=TRUE)
253          }
254
255 @
256
257 \section{Sanitization}
258 <<>>=
259 insane <- data.frame(Name=c("Ampersand","Greater than","Less than","Underscore","Per cent","Dollar","Backslash","Hash", "Caret", "Tilde","Left brace","Right brace"),
260                                 Character = I(c("&",">",                "<",            "_",            "%",            "$",            "\\", "#",      "^",            "~","{","}")))
261 colnames(insane)[2] <- paste(insane[,2],collapse="")
262 @
263
264 <<pxti,results=tex>>=
265 print( xtable(insane))
266 @
267 Sometimes you might want to have your own sanitization function
268 <<>>=
269 wanttex <- xtable(data.frame( label=paste("Value_is $10^{-",1:3,"}$",sep="")))
270 @
271 <<results=tex>>=
272 print(wanttex,sanitize.text.function=function(str)gsub("_","\\_",str,fixed=TRUE))
273 @
274
275 \subsection{Markup in tables}
276
277 Markup can be kept in tables, including column and row names, by using a custom sanitize.text.function:
278
279 <<>>=
280 mat <- round(matrix(c(0.9, 0.89, 200, 0.045, 2.0), c(1, 5)), 4)
281 rownames(mat) <- "$y_{t-1}$"
282 colnames(mat) <- c("$R^2$", "$\\bar{R}^2$", "F-stat", "S.E.E", "DW")
283 mat <- xtable(mat)
284 @
285 <<results=tex>>=
286 print(mat, sanitize.text.function = function(x){x})
287 @
288
289 % By David Dahl to demonstrate contribution from David Whitting, 2007-10-09.
290 You can also have sanitize functions that are specific to column or row names.  In the table below, the row name is not sanitized but column names and table elements are:
291 <<>>=
292 money <- matrix(c("$1,000","$900","$100"),ncol=3,dimnames=list("$\\alpha$",c("Income (US$)","Expenses (US$)","Profit (US$)")))
293 @
294 <<results=tex>>=
295 print(xtable(money),sanitize.rownames.function=function(x) {x})
296 @
297
298 \section{Format examples}
299 \subsection{Adding a centering environment }
300 <<results=tex>>=
301    print(xtable(lm.D9,caption="\\tt latex.environment=NULL"),latex.environment=NULL)
302     print(xtable(lm.D9,caption="\\tt latex.environment=\"\""),latex.environment="")
303     print(xtable(lm.D9,caption="\\tt latex.environment=\"center\""),latex.environment="center")
304 @
305 \subsection{Column alignment}
306
307 <<>>=
308 tli.table <- xtable(tli[1:10,])
309 @
310 <<>>=
311 align(tli.table) <- rep("r",6)
312 @
313 <<results=tex>>=
314 print(tli.table,floating=FALSE)
315 @
316 \subsubsection{Single string and column lines}
317 <<>>=
318 align(tli.table) <- "|rrl|l|lr|"
319 @
320 <<results=tex>>=
321 print(tli.table,floating=FALSE)
322 @
323 \subsubsection{Fixed width columns}
324 <<>>=
325 align(tli.table) <- "|rr|lp{3cm}l|r|"
326 @
327 <<results=tex>>=
328 print(tli.table,floating=FALSE)
329 @
330
331 \subsection{Significant digits}
332
333
334 Specify with a single argument 
335 <<>>=
336 digits(tli.table) <- 3
337 @
338 <<results=tex>>=
339 print(tli.table,floating=FALSE,)
340 @
341
342
343 or one for each column, counting the row names
344 <<>>=
345 digits(tli.table) <- 1:(ncol(tli)+1)
346 @
347 <<results=tex>>=
348 print(tli.table,floating=FALSE,)
349 @
350
351
352 or as a full matrix
353 <<>>=
354 digits(tli.table) <- matrix( 0:4, nrow = 10, ncol = ncol(tli)+1 )
355 @
356 <<results=tex>>=
357 print(tli.table,floating=FALSE,)
358 @
359
360 \subsection{Suppress row names}
361 <<results=tex>>=
362 print((tli.table),include.rownames=FALSE,floating=FALSE)
363 @
364
365 If you want a vertical line on the left, you need to change the align attribute.
366 <<>>=
367 align(tli.table) <- "|r|r|lp{3cm}l|r|"
368 @
369 <<results=tex>>=
370 print((tli.table),include.rownames=FALSE,floating=FALSE)
371 @
372
373 Revert the alignment to what is was before.
374 <<>>=
375 align(tli.table) <- "|rr|lp{3cm}l|r|"
376 @
377
378 \subsection{Suppress column names}
379 <<results=tex>>=
380 print((tli.table),include.colnames=FALSE,floating=FALSE)
381 @
382 \\
383 Note the doubled header lines which can be suppressed with, eg,
384 <<results=tex>>=
385 print(tli.table,include.colnames=FALSE,floating=FALSE,hline.after=c(0,nrow(tli.table)))
386 @
387
388 \subsection{Suppress row and column names}
389 <<results=tex>>=
390 print((tli.table),include.colnames=FALSE,include.rownames=FALSE,floating=FALSE)
391 @
392
393 \subsection{Rotate row and column names}
394 The {\tt rotate.rownames } and {\tt rotate.colnames} arguments can be
395 used to rotate the row and/or column names.
396
397 <<results=tex>>=
398 print((tli.table),rotate.rownames=TRUE,rotate.colnames=TRUE)
399 @
400
401 \subsection{Horizontal lines}
402
403 \subsubsection{Line locations}
404
405 Use the {\tt hline.after} argument to specify the position of the horizontal lines.
406
407 <<results=tex>>=
408 print(xtable(anova(glm.D93)),hline.after=c(1),floating=FALSE)
409 @
410
411 \subsubsection{Line styles}
412
413 The \LaTeX package {\tt booktabs} can be used to specify different 
414 line style tags for top, middle, and bottom lines.  Specifying
415 {\tt booktabs = TRUE} will lead to separate tags being generated
416 for the three line types.
417
418 Insert \verb|\usepackage{booktabs}| in your \LaTeX preamble and
419 define the {\tt toprule}, {\tt midrule}, and {\tt bottomrule}
420 tags to specify the line styles.
421
422 <<results=tex>>=
423 print(tli.table , booktabs=TRUE)
424 @
425
426 \subsection{Table-level \LaTeX}
427 <<results=tex>>=
428 print(xtable(anova(glm.D93)),size="small",floating=FALSE)
429 @
430
431
432 \subsection{Long tables}
433 Remember to insert \verb|\usepackage{longtable}| in your \LaTeX preamble.
434
435 <<longtable>>=
436
437 ## Demonstration of longtable support.
438 x <- matrix(rnorm(1000), ncol = 10)
439 x.big <- xtable(x,label='tabbig',
440         caption='Example of longtable spanning several pages')
441 @
442 <<results=tex>>=
443 print(x.big,tabular.environment='longtable',floating=FALSE)
444 @
445
446 %%
447 %% The column name alignment is off in the following example.
448 %% It needs some revision before exposing it. - CR, 7/2/2012
449 %%
450 %
451 %\subsubsection{Long tables with the header on each page}
452 %
453 %The {\tt add.to.row} argument can be used to display the header 
454 %for a long table on each page, and to add a "continued" footer
455 %on all pages except the last page. 
456 %
457 %<<results=tex>>=
458 %library(xtable)
459 %x<-matrix(rnorm(1000), ncol = 10)
460 %addtorow<-list()
461 %addtorow$pos<-list()
462 %addtorow$pos[[1]]<-c(0)
463 %addtorow$command<-c(paste(
464 %    "\\hline \n",
465 %    "  \\endhead \n",
466 %    "  \\hline \n",
467 %    "  {\\footnotesize Continued on next page} \n",
468 %    "  \\endfoot \n",
469 %    "  \\endlastfoot \n",sep=""))
470 %x.big2 <- xtable(x, label = "tabbig2", 
471 %    caption = "Example of longtable with the header on each page")
472 %print(x.big2, tabular.environment = "longtable", floating = FALSE,
473 %include.rownames=FALSE, add.to.row=addtorow, hline.after=c(-1) )
474 %@
475
476 \subsection{Sideways tables} 
477 Remember to insert \verb|\usepackage{rotating}| in your LaTeX preamble.
478 Sideways tables can't be forced in place with the `H' specifier, but you can 
479 use the \verb|\clearpage| command to get them fairly nearby.
480
481 <<>>=
482 x <- x[1:30,]
483 x.small <- xtable(x,label='tabsmall',caption='A sideways table')
484 @
485
486 <<results=tex>>=
487 print(x.small,floating.environment='sidewaystable')
488 @
489 \clearpage
490
491 \subsection{Rescaled tables} 
492 Specify a \code{scalebox} value to rescale the table.
493
494 <<>>=
495 x <- x[1:20,]
496 x.rescale <- xtable(x,label='tabrescaled',caption='A rescaled table')
497 @
498
499 <<results=tex>>=
500 print(x.rescale, scalebox=0.7)
501 @
502
503 \subsection{Table Width} 
504 The {\tt tabularx} tabular environment provides more alignment options,
505 and has a \code{width} argument to specify the table width.
506  
507 Remember to insert \verb|\usepackage{tabularx}| in your \LaTeX preamble.
508
509 <<>>=
510 df.width <- data.frame(
511   "label 1 with much more text than is needed" = c("item 1", "A"), 
512   "label 2 is also very long" = c("item 2","B"),
513   "label 3" = c("item 3","C"), 
514   "label 4" = c("item 4 but again with too much text","D"),
515   check.names = FALSE)
516
517 x.width <- xtable(df.width, 
518   caption="Using the 'tabularx' environment")
519 align(x.width) <- "|l|X|X|l|X|"  
520 @
521
522 <<results=tex>>=
523 print(x.width, tabular.environment="tabularx", 
524   width="\\textwidth")
525 @
526
527 \section{Suppressing Printing}
528 By default the {\tt print} method will print the LaTeX or HTML to standard
529 output and also return the character strings invisibly.  The printing to
530 standard output can be suppressed by specifying {\tt print.results = FALSE}.
531
532 <<>>=
533 x.out <- print(tli.table, print.results = FALSE)
534 @
535
536 Formatted output can also be captured without printing with the
537 {\tt toLatex} method.  This function returns an object of class
538 {\tt "Latex"}.
539
540 <<>>=
541 x.ltx <- toLatex(tli.table)
542 class(x.ltx)
543 x.ltx
544 @
545
546 \section{Acknowledgements}
547 Most of the examples in this gallery are taken from the {\tt xtable} documentation.
548 \section{R Session information}
549 <<results=tex>>=
550 toLatex(sessionInfo())
551 @
552 \end{document}