-
Notifications
You must be signed in to change notification settings - Fork 1
/
Guide_testDR.Rnw
1166 lines (1088 loc) · 41.7 KB
/
Guide_testDR.Rnw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[nogin]{beamer} %Instead of an article class, use beamer class
\usepackage{graphicx} %Bring in outside images
\usepackage{amssymb,amsmath} %Easy equation typsetter
\usepackage{listings}
\usepackage{colortbl} %More colours
\usetheme{mcgill} % Creates the McGill insignia behind the title page
\usecolortheme[RGB={238,44,44}]{structure}
\usetheme{PaloAlto}
\title{R, Sweave and Beamer}
\author{Christopher Lee}
\setbeamertemplate{itemize items}[ball]
\setbeamertemplate{enumerate items}[circle]
\begin{document}
\frame{\titlepage}
\begin{frame}
\frametitle{Table of Contents}
\tableofcontents
\end{frame}
\begin{frame}
\frametitle{Fork test}
here we are trying to edit directly on git hub 21 Jan 2014
\end{frame}
\begin{frame}[fragile]
\frametitle{Downloading packages}
\footnotesize
\begin{itemize}
\item R is found here:\\
\begin{sloppypar}
\url{http://cran.parentingamerica.com}
\end{sloppypar}
\item For Windows, find either TeX Live or MiKTeX here:
\begin{sloppypar}
\url{http://www.tug.org/texlive/acquire-netinstall.html}
\url{http://miktex.org/download}
\end{sloppypar}
\item For Mac OSX, find MacTex here:
\begin{sloppypar}
\url{http://tug.org/mactex/}
\end{sloppypar}
\item Beamer should already be preloaded. If not it may be found here:
\begin{sloppypar}
\url{https://bitbucket.org/rivanvx/beamer/wiki/Home}
\end{sloppypar}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Online Tutorials}
See the following resources for introductory tutorials and examples for Beamer:
\begin{itemize}
\begin{sloppypar}
\item \url{http://www.math.umbc.edu/~rouben/beamer/}
\item \url{http://www.informatik.uni-freiburg.de/~frank/ENG/latex-course/latex-course-3/latex-course-3_en.html}
\item \url{http://users.stat.umn.edu/~sandy/courses/8801/handouts/03.Beamer/beamer.pdf}
\item \url{http://www.wekaleamstudios.co.uk/supplementary-material/}
\end{sloppypar}
\end{itemize}
\end{frame}
\section{GGPLOT2}
\begin{frame}
\frametitle{Section 1}
\begin{center}
\Large
The Ggplot2 package
\end{center}
\end{frame}
\begin{frame}
\frametitle{Ggplot2}
\begin{block}{Data}
I am using CANSIM 202-0802 data to produce these graphs in R version 3.0.1
\end{block}
Find the data here:\\
\url{http://www.statcan.gc.ca/tables-tableaux/sum-som/l01/cst01/famil41a-eng.htm}
\end{frame}
\begin{frame}[fragile]
\frametitle{Example 1, Line graph}
<<echo=FALSE,warning=FALSE,message=FALSE,fig.height=5,fig.width=8>>=
setwd("~/Beamer-test")
library(xtable) #Supress messages is to avoid the ugly box detailing the package conflicts
library(ggplot2) #This code is not entirely necessary but makes the final product cleaner
library(reshape)
library(stringr)
library(scales)
library(Hmisc)
data2<-read.csv("cansim2123306067462968615.csv") #Load data from CANSIM 202-0802 Option 2
colnames(data2)<-c("Year","Geography","Line","Statistic","Population","Value")
#Small data cleaning...reordering and renaming certain factor levels
data2$Value<-as.numeric(as.character(data2$Value)) #Change value from factor to numeric
#Below I am reordering the factor levels of Geography and Population since I can't do it within Hmisc functions
data2$Geography<-ordered(data2$Geography,levels=c("Atlantic provinces","Newfoundland and Labrador",
"New Brunswick","Nova Scotia","Prince Edward Island",
"Prairie provinces","Alberta","Manitoba","Saskatchewan",
"British Columbia","Ontario","Quebec","Canada"))
data2$Population<-ordered(data2$Population,levels=c("Females","Males","Persons under 18 years",
"Persons 18 to 64 years","Persons 65 years and over",
"Persons in economic families","Persons under 18 years in female lone-parent families","Persons under 18 years in two-parent families","Unattached individuals","All persons"))
data2$Population<-revalue(data2$Population,c("Persons under 18 years in female lone-parent families"="Child in single mother families","Persons under 18 years in two-parent families"="Child in two-parent families"))
#End of data cleaning
data2<-subset(data2,!data2$Line=="Low income cut-offs before tax, 1992 base")
ggplot(data=subset(data2,data2$Geography=="Canada"&data2$Statistic=="Percentage of persons in low income"&
data2$Population=="All persons"),
aes(x=Year,y=Value/100,colour=Line,group=Line))+ #Year on x-axis, pov rate/100 on y-axis and each line gets a different colour
ylab("Poverty Rate")+ggtitle("Canadian Poverty Measures")+
geom_line()+ #All elements of geom_line taken from ggplot aesthetics arguments
geom_point()+ #All elements of geom_point taken from ggplot aesthetics arguemnts
scale_y_continuous(breaks=seq(0,max(data2$Value,na.rm=TRUE),.01),labels=percent)+
#Give a tick to every 1% pov rate on the y axis and convert pov rates (0<x<1) into percentages
theme(legend.direction="horizontal",legend.position="top",axis.text.x=element_text(angle=45))+
#Legend reads left to right on top of graph and angle x-axis ticks to 45 degrees
scale_x_continuous(breaks=seq(min(data2$Year,na.rm=TRUE),max(data2$Year,na.rm=TRUE),2))
#Give a tick to every 2 years on the x-axis, starting from the minimum Year to the maximum Year
@
\end{frame}
\begin{frame}[fragile]{Outline}
\frametitle{Example 2, Boxplots}
<<echo=FALSE,fig.height=5.75,fig.width=8>>=
ggplot(data=subset(data2,!data2$Line=="Market basket measure, 2011 base"&data2$Population=="All persons"&
(data2$Geography=="Canada"|data2$Geography=="Atlantic provinces"|
data2$Geography=="Prairie provinces"|data2$Geography=="Ontario"|
data2$Geography=="British Columbia"|data2$Geography=="Quebec")&
data2$Statistic=="Percentage of persons in low income"),
aes(x=Geography,y=Value/100,fill=Geography))+geom_boxplot()+facet_grid(.~Line)+
ggtitle("Poverty variance across broader geography")+ylab("Poverty Rate")+
scale_y_continuous(breaks=seq(0,max(data2$Value,na.rm=TRUE),0.05),labels=percent)+
theme(legend.direction="horizontal",legend.position="top",axis.text.x=element_text(angle=45))
@
\end{frame}
\begin{frame}[fragile]{Outline}
\frametitle{Example 3 Pie Charts}
<<echo=FALSE,fig.height=6>>=
ggplot(data=subset(data2,(Geography=="Atlantic provinces"|Geography=="Prairie provinces"|Geography=="British Columbia"|Geography=="Ontario"|Geography=="Quebec")&Statistic=="Number of persons in low income (x 1,000)"&Line=="Low income measure after tax"&Population=="All persons"&(Year=="1976"|Year=="1980"|Year=="1985"|Year=="1990"|Year=="1995"|Year=="2000"|Year=="2005"|Year==max(Year))),
aes(x=factor(1),y=Value,fill=Geography))+
geom_bar(stat="identity",width=1,position="fill")+
coord_polar(theta="y")+facet_wrap(~Year,ncol=4)+
ylab("")+xlab("")+ggtitle("Composition of the Poor across Geography")+
theme(axis.ticks = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank())
@
\end{frame}
\begin{frame}[fragile]
\frametitle{GGplot code}
\begin{block}{All these plots start with the same code}
\begin{verbatim}
ggplot(data=DATA,aes(x=X,y=Y,fill=FILL,
colour=COLOUR)
\end{verbatim}
\end{block}
\footnotesize
\begin{columns}[T]
\begin{column}{0.5\textwidth}
\begin{itemize}
\item DATA = self explanatory, our dataframe
\item X = What we want to plot on the x-axis
\item Y = What we want to plot on the y-axis
\item FILL = For our 3rd variable to create sections/bins ontop of the x and y axes.
\end{itemize}
\end{column}
\begin{column}{0.5\textwidth}
\begin{itemize}
\item COLOUR = Similar to FILL, it is created to map a third variable onto the plot.
\item Notice, this alone is not sufficient to create a plot. We have specified the parameters, but now must specify what type of plot we want
\end{itemize}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Geom code}
\begin{block}{Geom line, Geom boxplot, Geom point, Geom bar}
Here we pick which plots we want to use. Many arguments within the geom functions are very similar to the ones in the ggplot argument. Notice, if you have correctly specified your x, y and the third variable, you can leave \verb|geom_()| blank
\end{block}
\begin{itemize}
\item
\begin{verbatim}geom_line() : Line graph
\end{verbatim}
\item
\begin{verbatim}geom_boxplot() : Side-by-side \end{verbatim}
\begin{verbatim} boxplots
\end{verbatim}
\item
\begin{verbatim}geom_bar(stat='identity) : Bar charts/\end{verbatim}
\begin{verbatim} histogram
\end{verbatim}
\item
\begin{verbatim}geom_area() : Area plot
\end{verbatim}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Miscallaneous code}
Now with our plots we can tidy up the labels, axes, scales and legends
\scriptsize
\begin{columns}[T]
\begin{column}{0.5\textwidth}
\begin{block}{Imputs}
\begin{itemize}
\item \begin{verbatim} ylab \end{verbatim}
\item \begin{verbatim} xlab \end{verbatim}
\item \begin{verbatim} ggtitle \end{verbatim}
\item \begin{verbatim} guides \end{verbatim}
\item \begin{verbatim} theme \end{verbatim}
\item \begin{verbatim} scale_y_continuous \end{verbatim}
\item \begin{verbatim} scale_x_discrete \end{verbatim}
\end{itemize}
\end{block}
\end{column}
\begin{column}{0.5\textwidth}
\begin{block}{Explanation}
\begin{itemize}
\item Title for y-axis
\item Title for x-axis
\item Main Title
\item Controls legend
\item Remove or angle ticks
\item Control y-axis breaks and ticks
\item Contrl x-axis breaks and ticks
\end{itemize}
\end{block}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Example output}
<<echo=FALSE,fig.height=4>>=
ggplot(subset(data2,(Geography=="Ontario"|Geography=="Quebec")&
Line=="Low income measure after tax"&
Statistic=="Percentage of persons in low income"&
(Population=="Males"|Population=="Females")),
aes(x=Year,y=Value,colour=Population))+
geom_line()+ggtitle("This is my plot")+
ylab("Y")+xlab("X")+guides(fill=FALSE)+
scale_y_continuous(breaks=c(10,12,14))+
theme(legend.position="none",axis.text.x=element_text(angle=45))+
facet_grid(.~Geography)
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Example code explanation}
\scriptsize
From our dataset DATA, we graph the variable \emph{Year} on the x-axis and the variable \emph{Value} on the y-axis. We assign a seperate color for every factor level of the variable \emph{Population}.
\begin{verbatim}ggplot(data=DATA,aes(x=Year,y=Value,colour=Population))+\end{verbatim}
We specify that we want a line graph, and title the plot.
\begin{verbatim}geom_line()+gggtitle("This is my plot")\end{verbatim}
We title the y-axis \textbf{Y} and the x-axis \textbf{X}. We also suppress the legend.
\begin{verbatim}ylab("Y")+xlab("X")+guides(fill=FALSE)+\end{verbatim}
We control the y-axis and create ticks on the numbers 10, 12 and 14 of the variable \emph{Value}.
\begin{verbatim}scale_y_continuous(breaks=c(10,12,14))+ \end{verbatim}
We control the tick labels on the x-axis. We angle the tick labels 45 degrees
\begin{verbatim}theme(axis.text.x=element_text(angle=45))+
\end{verbatim}
We create several of these plots, each using a different factor level from the variable \emph{Geography}. Essentially, each plot is using different data according to a unique value of \emph{Geography}
\begin{verbatim}facet_grid(.~Geography)\end{verbatim}
\end{frame}
\begin{frame}
\frametitle{Result}
The graphic is now ready to be placed into a LaTeX environment. No additional wrapper is necessary to bring this graphic from R into LaTeX and eventually to exportable .pdf. We will reuse this code later.
\end{frame}
\begin{frame}[fragile]
\frametitle{Other resources}
For more information see the following links
\begin{itemize}
\item \url{http://www.cookbook-r.com/Graphs/}
\item \url{http://sharpstatistics.co.uk/r/ggplot2-guide/}
\item \url{http://www.ceb-institute.org/bbs/wp-content/uploads/2011/09/handout_ggplot2.pdf}
\end{itemize}
\end{frame}
\section{Xtable and Hmisc}
\begin{frame}
\frametitle{Section 2}
\begin{center}
\Large
Exporting Tables to LaTeX environments
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Xtable and Hmisc}
\begin{block}{Now what about tables?}
We've seen how to create graphics and plots using ggplot within R. Now lets see how to create tables ready to be exported into LaTeX. There are two packages in R designed for this. To use either, imput the following two lines of code
\begin{enumerate}
\item Xtable
\begin{verbatim}install.packages("xtable")
library(xtable)\end{verbatim}
\item Hmisc
\begin{verbatim}install.packages("Hmisc")
library(Hmisc)\end{verbatim}
\end{enumerate}
\end{block}
\end{frame}
\begin{frame}[fragile]
\frametitle{Exporting R tables as LaTeX tables }
\begin{itemize}
\item Tables are only slightly more tricky than plots, in that there are several base R functions to summarize data and create tables in the console. But that output is not immediately exportable to LaTeX
\item We look to Xtable and Hmisc, which allows us to wrap R tables within a function that translates it into LaTeX code.
\item Exportable objects can range from contingency tables to matrices, regression summaries, ANOVA tables and even raw data
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Xtable}
{\small List of base tables}
\begin{columns}[T]
\begin{column}{.5\textwidth}
\begin{block}{R function}
\begin{itemize}
\item \begin{verbatim}table()\end{verbatim}
\item \begin{verbatim}xtabs()\end{verbatim}
\item \begin{verbatim}prop.table()\end{verbatim}
\item \begin{verbatim}aggregate()\end{verbatim}
\item \begin{verbatim}anova()\end{verbatim}
\end{itemize}
\end{block}
\end{column}
\begin{column}{.5\textwidth}
\begin{block}{Description}
\begin{itemize}
\footnotesize
\item 2-way contingency table
\item 3-way contingency table
\item 2-way frequency table
\item Custom aggregate data
\item Analysis of variance wrapper around a regression object
\end{itemize}
\end{block}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile,shrink]
\frametitle{Xtable input}
\begin{block}{}
Take an R object of class dataframe, matrix, array, aov, lm...\\
and then enter \verb|xtable(x)| to provide LaTeX output. You are given a series of options for the output.
\end{block}
\begin{columns}[T]
\begin{column}{.5\textwidth}
\begin{itemize}
\item Digits
\item Line divisions
\item Floating environment
\end{itemize}
\end{column}
\begin{column}{.5\textwidth}
\begin{itemize}
\item Captions
\item Alignment of columns
\item others
\end{itemize}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile,shrink]
\frametitle{Wrapping xtable in print}
\small
Wrapping xtable in the print function is essential because it allows us to specify the LaTeX object to not float the table. A floated table is within a table environment and is sandwiched between \verb|\begin{table}| and \verb|\end{table}|\\[\baselineskip]
Once a table is floated there is very little we can do with it. The biggest problem is always \textbf{Overfull Hbox}. Tables are often too long to fit to the page width. Since Beamer is in a presentation format, its a bad idea to play around too much with the page size.\\[\baselineskip]
Sometimes we have Overfull Vbox where the table is too long, but this is easily corrected by specifying xtable to deliver output in "longtable" format and splitting the table across multiple frames. This cannot be done with wide tables.
\end{frame}
\begin{frame}[fragile]
\frametitle{Wrapping xtable in print Cont...}
We can shrink this "un-floated" table by first loading the \textbf{graphicx} package into LaTeX and then use the \textbf{resize} argument. It should look something like this.
\begin{verbatim}
\documentclass{beamer}
\usepackage{graphicx}
\begin{document}
\resizebox{\linewidth}{!}{%
<<echo=FALSE,warning=FALSE>> =
print(xtable(x),floating=FALSE)
@
}
\end{verbatim}
\end{frame}
\begin{frame}[fragile,shrink]
\frametitle{Xtable example part 1}
First lets create the table in R. It doesn't look too nice.
\begin{verbatim}table<-with(subset(data2,data2$Year>=2000&data2$Geography=="Canada"&
data2$Statistic=="Percentage of persons in low income"&
as.character(data2$Line)=="Low income cut-offs after tax, 1992 base"),
xtabs(Value~Population+Year))
\end{verbatim}
<<echo=FALSE,warning=FALSE>>=
table<-with(subset(data2,data2$Year>=2000&data2$Geography=="Canada"&data2$Statistic=="Percentage of persons in low income"&
as.character(data2$Line)=="Low income cut-offs after tax, 1992 base"),xtabs(Value~Population+Year))
table
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Xtable example part 2}
\small
Now lets wrap our xtab() table within xtable. Again this looks very ugly. We have forgotten to change some options in the chunk code.
\begin{verbatim}
table2<-
xtable(table,digits=1,align="l|rrrrrrrrrrrr")
\end{verbatim}
<<echo=FALSE,warning=FALSE>>=
table2<-xtable(table,digits=1,align="l|rrrrrrrrrrrr")
table2
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Example part 3}
\small
We have to modify our R chunk code for LaTeX to properly read xtable. The table looks right now, except that it is far too large for the frame
\begin{verbatim}
<<echo=FALSE,warning=FALSE, results='asis'>> =
table2<-
xtable(table,digits=1,align="l|rrrrrrrrrrrr")
@
\end{verbatim}
<<echo=FALSE,warning=FALSE,results='asis'>>=
table2
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Example part 4}
This shows our Overfull Hbox problem. To remedy this we wrap the xtable within print, specify floating=FALSE and resize the table
\begin{verbatim}
\resizebox{\linewidth}{!}{%
<<echo=FALSE,warning=FALSE,results='asis'>> =
print(table2,floating=FALSE)
@
}
\end{verbatim}
\resizebox{\linewidth}{!}{%
<<echo=FALSE,warnings=FALSE,results='asis'>>=
print(table2,floating=FALSE)
@
}
\end{frame}
\begin{frame}
\frametitle{Floating}
Remember, the \textbf{resize} command will only work on a "non-floating" object. Therefore if you have an Overfull hbox, you must first wrap your table in print() and specify floating=FALSE.\\[\baselineskip]
I'll go over the R chunk code and Sweave code in the next section.
\end{frame}
\begin{frame}[fragile]
\frametitle{A simpler solution: Xtable font size}
Sometimes the resize command is unecessary and a simpler solution is available. Xtable allows for us to change the font size from normal size to {\tiny very small} to {\Large very large}
\begin{block}{xtable(...,size=" ")}
By changing the font size of the table, we can easily remedy minor Overfull Hbox and Vbox. There are 10 sizes.
\begin{columns}[T]
\begin{column}{.25\linewidth}
\begin{itemize}
\item {\tiny tiny}
\item {\scriptsize scriptsize}
\item {\footnotesize footnotesize}
\item {\small small}
\end{itemize}
\end{column}
\begin{column}{.25\linewidth}
\begin{itemize}
\item {\normalsize normal}
\item {\large large}
\item {\Large Large}
\end{itemize}
\end{column}
\begin{column}{.5\linewidth}
\begin{itemize}
\item {\LARGE LARGE}
\item {\huge huge}
\item {\Huge Huge}
\end{itemize}
\end{column}
\end{columns}
\end{block}
\end{frame}
\begin{frame}[fragile]
\small
\frametitle{Dressing up a table}
Lets say we have a properly sized vanilla table
\begin{columns}[T]
\begin{column}{0.5\textwidth}
<<echo=FALSE,warnings=FALSE,results='asis'>>=
tab1<-subset(data2,data2$Geography=="Canada"&data2$Statistic=="Percentage of persons in low income"&
data2$Population=="All persons"&data2$Year>=1995&(data2$Year<=2005|data2$Year==2011))
tab1<-tab1[,c(1,3,6)] #Select variables of interest
tab1$Line<-factor(tab1$Line) #Refactorize column to remove empty factor level
tab2<-xtabs(Value~Year+Line,data=tab1) #Creating 3-way table
tab2[tab2==0]<-NA #For purposes of exercise, turn all 0s into NA
colnames(tab2)<-c("LICO","LIM","MBM")
xtable(tab2,size="small")
@
\end{column}
\begin{column}{0.45\textwidth}
We will try to add a few features to the table:
\begin{itemize}
\item Percentage signs
\item Captions
\item Line divisions
\item A little colour
\end{itemize}
To use the following code add \verb|\usepackage{colortbl}| to the preamble and \verb|library(stringr)| to the chunk code
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Dressing up a table: Result}
\begin{columns}[T]
\begin{column}{.5\textwidth}
<<echo=FALSE,warnings=FALSE,results='asis'>>=
tab3<-apply(tab2, 2, function(u) ifelse(!is.na(u),sprintf( "%.1f%%", u),u))
pos<-as.list(seq(1,nrow(tab3),by=2))
com<-rep("\\rowcolor[gray]{.9}",length(pos))
print(xtable(tab3,caption="Poverty Lines",align="l||c|c|c"),hline.after=c(-1,0,11,nrow(tab2)),size="small",
add.to.row=list(pos=c(list(-1,8),pos),
command=c("\\rowcolor[rgb]{1,.8,.8}","\\rowcolor[rgb]{.8,1,0}",com)))
@
\end{column}
\begin{column}{.45\textwidth}
\scriptsize
\begin{lstlisting}
tab3<-apply(tab2, 2, func)
func<-function(u){
ifelse(!is.na(u),
sprintf("%.1f%%",u),u)}
pos<-as.list(seq(1,
nrow(tab3),by=2))
com<-rep(
"\\rowcolor[gray]{.9}",
length(pos))
print(xtable(tab3,
caption="Poverty Lines",
align="l||c|c|c",
size="small"),
hline.after=
c(-1,0,11,nrow(tab2)),
add.to.row=list(
pos=c(list(-1,8),pos),
command=c(
"\\rowcolor[rgb]{1,.8,.8}",
"\\rowcolor[rgb]{.8,1,0}",
com)))
\end{lstlisting}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Dressing up a table: Explanation}
\footnotesize
First we define a function that will paste a \% on every non-NA element
\begin{verbatim}
tab3<-apply(tab2, 2, function(u)
ifelse(!is.na(u),sprintf( "%.1f%%", u),u))
\end{verbatim}
Then we need to specify the rows in the table which are alternating
\begin{verbatim}
pos<-as.list(seq(1,nrow(tab3),by=2))
\end{verbatim}
Then we pick the color for the alternating rows defined by \verb|pos|
\begin{verbatim}
com<-rep("\\rowcolor[gray]{.9}",length(pos))
\end{verbatim}
Now call xtable and use the caption option to define your caption
\begin{verbatim}
print(xtable(tab3,caption="Poverty Lines",
\end{verbatim}
Create vertical lines between certain columns
\begin{verbatim}
align="l||c|c|c",
\end{verbatim}
Also specify a different font size for the table and close xtable options
\begin{verbatim}
size="small"),
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Dressing up a table: Explanation cont.}
\footnotesize
Now in the print options, create horizontal lines to divide key rows
\begin{verbatim}
hline.after=c(-1,0,11,nrow(tab2)),
\end{verbatim}
Select the header, another row and our alternating rows
\begin{verbatim}
add.to.row=list(pos=c(list(-1,8),pos),
\end{verbatim}
Now lets select colors for our header, another row and alternating rows
\begin{verbatim}
command=c("\\rowcolor[rgb]{1,.8,.8}",
"\\rowcolor[rgb]{.8,1,0}",
com)))
\end{verbatim}
Now we are finished.
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc}
The Hmisc equivalent of the \verb|xtable()| wrapper is the \verb|latex()| function. It operates in a similar manner to xtable. There are many advanced features in Hmisc that are unavailable to xtable such as multi-line headers, very simple cell selection plus all the functionality of xtable. Hmisc output generally looks cleaner than xtable output.
With our last example table: \verb|tab2|, we can write a basic latex table with Hmisc using the following code.
\begin{verbatim}
latex(tab2, file= '')
\end{verbatim}
\verb|tab2| is the object we want wrapped, and \verb|file= ''| stops Hmisc from creating a separate output postcript file. In other words, it means we will get standard latex output.
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc and Floating}
\small
Like with Xtable, we may run into scenarios where we have Overfull Hbox. In that case we can resize our R table only if our table is non-floating. it In order to specify the output of \verb|latex()| to be a non-floating object, we write:
\begin{verbatim}
latex(...,table.env=FALSE,center=FALSE)
\end{verbatim}
So instead of your last 3 lines of code looking like
\begin{verbatim}
\end{tabular}
\end{center}
\end{table}
\end{verbatim}
You are simply left with
\begin{verbatim}
\end{tabular}
\end{verbatim}
Now we can squeeze in a resize for this tabular environment, then center and table it later if we want.
Like with xtable, these two options are necessary if you need to tinker or resize the table.
\end{frame}
\begin{frame}
\frametitle{Hmisc (latex) inputs: Useful options}
\small
\begin{columns}[T]
\begin{column}{.5\textwidth}
\begin{itemize}
\item file: \emph{See slides above}
\item table.env: \emph{See slides above}
\item center: \emph{See slides above}
\item size: \emph{Same as xtable}
\item vbar: \emph{Vertical line divisions}
\item rowname: \emph{Supress row names}
\end{itemize}
\end{column}
\begin{column}{.5\textwidth}
\begin{itemize}
\item extracolheads: \emph{Add sub-headers}
\item cellTexCmds \emph{Format table cells}
\item booktabs: \emph{Different table style}
\item ctable: \emph{Different table style}
\end{itemize}
\end{column}
\end{columns}
\end{frame}
\begin{frame}
\frametitle{Hmisc (latex) inputs: Group commands}
\small
\begin{columns}[T]
\begin{column}{.5\textwidth}
\begin{block}{Column Groups}
\begin{itemize}
\item cgroup: \emph{Name your column groups}
\item n.cgroup: \emph{Select your column groups}
\item cgroupTexCmd: \emph{Format your column groups}
\item cgroup.just: \emph{Align your column groups}
\end{itemize}
\end{block}
\end{column}
\begin{column}{.5\textwidth}
\begin{block}{Row Groups}
\begin{itemize}
\item rgroup: \emph{Name your row groups}
\item n.rgroup: \emph{Select your row groups}
\item rgroupTexCmd: \emph{Format your row groups}
\item rowlabel: \emph{Simple header for row names}
\end{itemize}
\end{block}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc example part 1}
\small
Lets start with some subsetted data. Here are the first couple rows.
<<echo=FALSE,warning=FALSE,size='tiny'>>=
tab4<-subset(data2,(data2$Geography=="Ontario"|data2$Geography=="Quebec")&
(data2$Statistic=="Percentage of persons in low income"|data2$Statistic=="Number of persons in low income (x 1,000)")&
!data2$Line=="Market basket measure, 2011 base"&
data2$Population=="All persons"&
data2$Year>=2005)
row.names(tab4)<-NULL
head(tab4[1:3])
head(tab4[4:6])
@
\end{frame}
\begin{frame}[fragile,shrink]
\frametitle{Hmisc example part 2}
\small
The data is in long format so we will call \emph{cast} from the \emph{reshape} package in order to display the data how we want
<<echo=FALSE,warning=FALSE,size='tiny'>>=
tab5<-cast(tab4,Geography+Year~Line+Statistic,value="Value")
colnames(tab5)[3:6]<-c("LICO Persons in low income","LICO Pov. rate","LIM Persons in low income","LIM Pov. rate")
row.names(tab5)<-NULL
tab5[1:4]
tab5[4:6]
@
\end{frame}
\begin{frame}
\frametitle{Hmisc example part 3}
\small
For the sake of comparison, lets first create the table in Xtable
\begin{table}
\resizebox{\linewidth}{!}{%
<<echo=FALSE,warning=FALSE,results='asis'>>=
print(xtable(tab5,align="cc|c||cccc",size="small",digits=1),hline.after=c(-1,0,7,nrow(tab5)),floating=FALSE,include.rownames=FALSE)
@
}
\caption{Using Xtable}
\end{table}
This looks adequate, but lets see if Hmisc can do better...
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc example part 4}
\small
\begin{table}
\resizebox{\linewidth}{!}{%
<<echo=FALSE,results='asis'>>=
tab6<-cast(tab4,Geography+Year~Line+Statistic,value="Value")
tab6<-tab6[,-1] #Remove Geography
colnames(tab6)<-c("Year","Number of persons in low income","Poverty rate","Number of persons in low income","Poverty rate")
latex(tab6,file='',extracolheads=c('','(x 1,000)','\\%','(x 1,000)','\\%'),
cgroup=c('','LICO','LIM'),n.cgroup=c(1,2,2),
rgroup=c('Ontario','Quebec'),n.rgroup=c(7,7),
table.env=FALSE,center='none',
rowlabel='',col.just=c('c','c','c','c','c'),
size='tiny')
@
}
\caption{Using Hmisc}
\end{table}
This looks a bit nicer I think. Lets go over the code in detail
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc example: code}
\small
First, lets cast the data, drop \emph{Geography} and rename headers.
\begin{verbatim}
tab6<-cast(tab4,Geography+Year~Line+Statistic,
value="Value")
tab6<-tab6[,-1]
colnames(tab6)<-
c("Year","Number of persons in low income",
"Poverty rate","Number of persons in low income",
"Poverty rate")
\end{verbatim}
Now lets wrap our \emph{tab6} in Hmisc's latex function and avoid any unecessary file creation. Lets also set a font size.
\begin{verbatim}
latex(tab6,file='',size ='tiny',
\end{verbatim}
Add extra headers beneath our new column names.
\begin{verbatim}
extracolheads=c('','(x 1,000)','\\%',
'(x 1,000)','\\%'),
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Hmisc example: code cont...}
\small
Now lets look at multi-line headers. We want the first 7 rows in one group and the next 7 in another. Then name the respective groups. We want the first row, then the next 2 and the next 2 in groups so name those as well
\begin{verbatim}
n.rgroup=c(7,7),rgroup=c('Ontario','Quebec'),
n.cgroup=c(2,2),cgroup=c('','LICO','LIM'),
\end{verbatim}
Remove any header for the rownames and center all the columns
\begin{verbatim}
rowlabel='',col.just=c('c','c','c','c','c'),
\end{verbatim}
Finally, and most importantly, remove the float (ie. remove \verb|\begin{table} \begin{center}| and the ends as well) so we can resize it later.
\begin{verbatim}
table.env=FALSE,center='none')
\end{verbatim}
\end{frame}
\section{Sweave}
\begin{frame}
\frametitle{Section 3}
\begin{center}
\Large
Using Sweave and Knitr
\end{center}
\end{frame}
\begin{frame}
\frametitle{Sweave and Knitr}
Now knowing how to create plots and tables in a LaTeX format, how exacty do we get our R code into LaTeX in the first place? The generic R script file will not work. To get started
\begin{itemize}
\item Open R
\item Instead of a script file, open up an R Sweave file with extension .Rnw
\item Go to Tools $\Rightarrow$ Options $\Rightarrow$ Sweave
\item Select "Weave Rnw files using" $\Rightarrow$ knitr
\end{itemize}
You must have LaTeX in order to run this type of file. We will use \textbf{knitr} to move R code into LaTeX code, rather than the default \textbf{Sweave} which has a few annoying problems
\end{frame}
\begin{frame}[fragile]
\frametitle{Sweave layout}
\begin{block}{}
In a .Rnw file, you must use LaTeX code. To use R code instead, you must create a "Chunk".
\end{block}
\begin{columns}[T]
\begin{column}{.5\textwidth}
\begin{itemize}
\item To begin the chunk, type:
\begin{verbatim}<<>>=\end{verbatim}
\item To end the chunk, type:
\begin{verbatim}@\end{verbatim}
\end{itemize}
\end{column}
\begin{column}{.5\textwidth}
On your screen it should look like this:
\includegraphics[width=\textwidth]{GuidePic1.pdf}
\end{column}\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{R to Sweave}
\begin{itemize}
\item Within the chunk, the R code is exactly the same as if you were writing R code in a script file.
\item It is better to create a chunk for every table or plot, rather than putting all your R code and figures/tables in the same chunk.
\item Plots are almost never sized correctly to the page. You will have to tweak with the chunk code in order to display plots with your desired dimensions.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Chunk Code}
\scriptsize
You can control the output of the R code within your chunk.
\begin{verbatim} << options go here >>= \end{verbatim}
A couple options:
\begin{columns}[T]
\begin{column}{.3\textwidth}
\begin{itemize}
\item echo
\item warnings
\item results
\item include
\item size
\item message
\item fig.height
\item fig.width
\end{itemize}
\end{column}
\begin{column}{.7\textwidth}
\begin{itemize}
\item Prints the R code in the output
\item Prints the warnings in the output
\item Whether to display the chunk output
\item How to display the chunk output
\item Font size of chunk output
\item Prints messages in the output
\item Change height of figure
\item Change width of figure
\end{itemize}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Chunk code example}
\begin{verbatim}<<echo=FALSE,warning=FALSE,message=FALSE,
fig.height=4,size='tiny'>>=\end{verbatim}
\begin{itemize}
\item The actual R chunk code is not displayed
\item Warnings from the R chunk code are not displayed
\item Messages from the R chunk code are not displayed
\item The figure in the chunk has a height of 4 inches
\item The font size for the chunk output is {\tiny tiny}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Finally, compiling the .pdf}
\begin{itemize}
\item After you have set up your R chunk with LaTeX friendly plots and tables, the very last step is to click \textbf{Compile PDF}
\item This will create several files, a .log file, a .tex file, several auxilary files and the .pdf file.
\item Any plot output from your R chunks will also be saved in a folder (if unspecified) called \textbf{figure} in whichever directory you are working from.
\end{itemize}
\end{frame}
\section{Beamer}
\begin{frame}
\frametitle{Section 3}
\begin{center}
\Large
Beamer and LaTeX
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{LaTeX Preamble}
Here's a very basic intro to LaTeX for the purposes of Beamer.
\begin{enumerate}
\item Define a document class. We want beamer
\item Run any packages you require for LaTeX
\item Choose your desired beamer color and theme
\item Create a title
\item Create an author
\item Run any other beamer options
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\frametitle{LaTeX Preamble example}
\begin{enumerate}
\item \verb|\documentclass{beamer}|
\item \verb|\usepackage{graphicx}|
\item \verb|\usetheme{PaloAlto}|
\item \verb|\title{This is my title}|
\item \verb|\author{This is my name}|
\item \verb|\setbeamertemplate{itemize items}[ball]|
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\frametitle{Title and ToC}
Now that the preamble is finished, lets get onto the code:
\begin{enumerate}
\item \verb|\begin{document}|
\item \verb|\frame{\titlepage}|
\item \verb|\tableofcontents|
\end{enumerate}
\begin{itemize}
\item No. 2 provides us a title page which displays some of the things in our preamble
\item No. 3 provides us a table of contents which will list the sections and subsections of the document.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{The frame}
\footnotesize
In beamer, you will create your presentation frame by frame.
\begin{enumerate}
\item Start a frame environment with \verb|\begin{frame}|
\item Create a frame title with \verb|\frametitle{My frame title}|
\item Now you are within the frame. You can then write anything and it will display within the frame.
\item Finally, close the frame environment with \verb|\end{frame}|
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\frametitle{The frame Cont...}
\footnotesize
We can dress up our frame a bit.
\begin{enumerate}
\item Start a block with \verb|begin{block}{My block title}|
\item Write anything in the block.
\item Maybe you want bulletpoints with \verb|\begin{itemize}|
\item Now within the itemize environment, write items\\
\verb|\item This is my 1st bulletpoint|\\
\verb|\item This is my 2nd bulletpoint|\\
\item Now close the itemize environment with \verb|\end{itemize}|
\item Now close the block environment with \verb|\end{block}|
\end{enumerate}
The following frame is our end result
\end{frame}
\begin{frame}[fragile]
\frametitle{My frame title}
Now you are within the frame. You can then write anything and it will display within the frame.
\begin{block}{My block title}
Write anything in the block.
\begin{itemize}
\item This is my 1st bulletpoint