-
Notifications
You must be signed in to change notification settings - Fork 12
/
RcourseBerry_Mathias.Rnw
3410 lines (2845 loc) · 121 KB
/
RcourseBerry_Mathias.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[xcolor=table, xcolor=dvipsnames]{beamer} % , handout, draft
\usetheme{Madrid} % Madrid, Warsaw, Berlin
\usecolortheme{beaver}
\usepackage[latin1]{inputenc} % windows
%\usepackage[utf8]{inputenc} %linux
\usepackage[T1]{fontenc} % for textbackslash
\usepackage[german, english]{babel}
\usepackage{natbib} % bibliography issues. cite in a scientific way
\usepackage{rotating} % rotate tables pictures..
\usepackage{float} % placing floats (table and figures) at exactly the place i want them to
\usepackage{lmodern} % warnings disappear within the beamer class
\usepackage[capitalise, noabbrev]{cleveref} % smart referencing
\usepackage{colortbl, tabu, multirow} % For coloring table rows and text inside them
\usepackage[labelfont=scriptsize, font=scriptsize]{caption}
\usepackage{url, hyperref, textcomp, amsmath, listings, datetime, graphicx, booktabs, xcolor}
%\usepackage{booktabs} % for thick lines in tables
%\usepackage{wasysym, breakurl}
\hypersetup{pdfstartview={XYZ null null 1}}
\hypersetup{colorlinks=true, linkcolor=blue, urlcolor=blue}
\setbeamertemplate{footline}[text line]{%
\parbox{\linewidth}{\vspace*{-8pt}\hfill \hyperlink{toc}{TOC} ~~ \insertframenumber / \inserttotalframenumber~~~~~~~~~}}
\setbeamertemplate{navigation symbols}[only frame symbol]
\beamersetleftmargin{0.3cm}
\beamersetrightmargin{0.3cm}
% Reduce spacing in table of contents (toc) http://tex.stackexchange.com/questions/51452
\usepackage{etoolbox}
\makeatletter
\patchcmd{\beamer@sectionintoc}{\vskip1.5em}{\vskip0.1em}{}{} % vskip0.5em
\makeatother
% white letters in enumerate bullet points
\setbeamercolor{item projected}{fg=white}%fg=blue,bg=red!75!black} % fg=white
% Block title color
\setbeamercolor{block title}{fg=white}%fg=blue,bg=red!75!black} % white
% define an environment for the exercises
\newcounter{exercisecount}
\setcounter{exercisecount}{0}
\newenvironment{exercise}[1]
{% This is the begin code
\stepcounter{exercisecount}
\begin{block}{Exercise \arabic{exercisecount}: #1}
}
{% This is the end code
\end{block} }
% format inline R command names in blue courier:
\newcommand{\rcode}[1]{\texttt{\textcolor{Blue}{#1}}} % or use Blue
% Table of data and object types, with higlighted rows
\newcommand{\datatypes}[9]{
\begin{frame}\frametitle{Data types}
\begin{center}
\begin{tabu}{| l | l | l | l |} \hline
\textbf{Description} & \textbf{example} &\textbf{\rcode{typeof}} &\textbf{\rcode{class}} \\\hline \hline
\rowfont{\color{#1}} integer number & 4:6 & integer & integer \\ \hline
\rowfont{\color{#2}} decimal & 8.7 & double & numeric \\ \hline
\rowfont{\color{#3}} character string & "homer rocks" & character & character \\ \hline
\rowfont{\color{#4}} category & factor("left") & integer & factor \\ \hline
\rowfont{\color{#5}} complex & 5+3i & complex & complex \\ \hline
\rowfont{\color{#6}} logical & c(T, F, FALSE, TRUE) & logical & logical \\ \hline
\rowfont{\color{#7}} not available & NA & logical & logical \\ \hline
\rowfont{\color{#8}} empty set & NULL & NULL & NULL \\
\hline
\end{tabu}
\end{center}
\color{#9}
%See also e.g. Uwe Ligges (2006) - Programmieren mit R\\
\rcode{as.character}\texttt{(3.14)} converts a data type; \rcode{is.integer}\texttt{(4:6)} checks.
\rcode{str} shows an abbreviaton of \rcode{class}.\\
\rcode{mode} (for users) is like \rcode{typeof} (R internal), but combines integer and double to numeric (VeryAdvanced: also combines closure, special and builtin to function). Other rare typeofs: raw, environment, promise, ...
\end{frame}
}
\newcommand{\objecttypes}[7]{
\begin{frame}\frametitle{Object types}
\begin{center}
%\begin{tabu}{| l | m{4cm} | m{3cm} | l |} \hline
\begin{tabu}{| l | l | l | l |} \hline
\textbf{Object} & \textbf{example} & \textbf{\rcode{typeof}} & \textbf{\rcode{class}}\\ \hline \hline
\rowfont{\color{#1}} vector & see data types & data type & data type \\ \hline
\rowfont{\color{#2}} matrix & matrix(9:15, ncol=2) & integer & matrix \\ \hline
\rowfont{\color{#3}} table & \small data.frame(C1=4:5, C2=c("a","b")) & list & data.frame \\ \hline
\rowfont{\color{#4}} list & list(el1=7:15, el2="big") & list & list \\ \hline
\rowfont{\color{#5}} function & function(x) 12+0.5*x & closure & function \\ \hline
\rowfont{\color{#6}} ... & lm(b $\sim$ a) & list & lm \\ \hline
\end{tabu}
\end{center}
\color{#7} \small A matrix consists of only one data type. If you accidentally change one element to a character, all are converted and calculations are not possible any more. DataFrames can have multiple data types, but a column in itself also has only one type. Lists can combine anything, even other lists. \rcode{is.vector}\texttt{(Object)} returns TRUE or FALSE, \rcode{as.matrix}\texttt{(Object)} converts the class of an object by force.
\end{frame}
}
% Topics yet to be included:
% Read xls files (Excel), including sheet number
% linear regression: calculate, coef + text, berryFunctions::linReg
% See where echo=3:4 is useful, see http://yihui.name/knitr/demo/output/
% remove empty lines between code and output. apparently hard to get rid of without turning off syntax highlighting
%------------------------------------------------------------%
%------------------------------------------------------------%
\title{R introductionary course}
\author{Berry Boessenkool, \texttt{[email protected]}}
\date{October 2015}
%------------------------------------------------------------%
%------------------------------------------------------------%
\begin{document}
%------------------------------------------------------------%
%------------------------------------------------------------%
%\def\newblock{} % beamer---natbib bugfix
<<setup, include=FALSE>>=
#install.packages("berryFunctions")
# set global chunk options maybe use out.width='.55\\linewidth'
opts_chunk$set(fig.path='./fig/', fig.align='center', fig.show='hold', out.width='.8\\textwidth', fig.height=5, fig.width=9, cache=TRUE)
options(replace.assign=FALSE, width=40)
#options(width = 60)
# set locale to US, which makes sure that eg month names are in english
Sys.setlocale("LC_ALL", "US") # Windows
# set r course working directory
# if(.Platform$OS.type=="unix") if(Sys.getenv("username") == "hydro")
setwd("S:/Dropbox/Public/R_course_Berry")
# par standards
par(las=1, mar=c(4,4,.5,0.5), main="")
ThemeBerry <- list(highlight="
\\definecolor{fgcolor}{rgb}{0, 0, 0}
\\newcommand{\\hlnum}[1]{\\textcolor[rgb]{0,0,0}{#1}}
\\newcommand{\\hlstr}[1]{\\textcolor[rgb]{0.545,0.137,0.137}{#1}}
\\newcommand{\\hlcom}[1]{\\textcolor[rgb]{0,0.392,0}{\\textit{#1}}}
\\newcommand{\\hlopt}[1]{\\textcolor[rgb]{0,0,0}{#1}}
\\newcommand{\\hlstd}[1]{\\textcolor[rgb]{0,0,0}{#1}}
\\newcommand{\\hlkwa}[1]{\\textcolor[rgb]{1,0,0}{\\textbf{#1}}}
\\newcommand{\\hlkwb}[1]{\\textcolor[rgb]{0,0,0}{#1}}
\\newcommand{\\hlkwc}[1]{\\textcolor[rgb]{1,0,1}{#1}}
\\newcommand{\\hlkwd}[1]{\\textcolor[rgb]{0,0,1}{#1}}
", background="#F5F5F5", foreground="black")
knit_theme$set(ThemeBerry)
rm(ThemeBerry)
@
\AtBeginSection[]
{
\setbeamertemplate{headline}[default]
% \begin{frame}<beamer>{Inhalt} % frame is only shown in beamer mode (useful for creating handouts)
\begin{frame}\frametitle{Outline}
\small
\tableofcontents[hideothersubsections, sectionstyle=show/shaded]
% currentsection, currentsubsection, hideothersubsections, sectionstyle=show/hide, subsectionstyle=show/shaded, hideallsubsections
% see section 10.5 of the beamer user guide.
\end{frame}
}
\AtBeginSubsection[]
{
\begin{frame}%[shrink]
\frametitle{Outline}
\small
\tableofcontents[sectionstyle=show/shaded, subsectionstyle=show/shaded/hide]
\end{frame}
}
%------------------------------------------------------------%
\begin{frame}
\titlepage
\begin{center}
\alert{This is the material originally from Mathias Seibert,\\ slightly changed so the document is compiling}\\[1em]
German Centre for Geosciences Potsdam (GFZ) \\
One-week course held in Bishkek, Kygyzstan, in December 2013 \\
within the CaWa research framework:
\href{http://www.cawa-project.net/story/300}{www.cawa-project.net}\\[1em]
\tiny PDF created on \today\ at \currenttime\ \\
\small get current main \href{https://dl.dropboxusercontent.com/u/4836866/R_course_Berry/RcourseBerry.pdf}{pdf} (\href{http://bit.ly/rcBerry}{bit.ly/rcBerry}) or
\href{https://dl.dropboxusercontent.com/u/4836866/R_course_Berry/RcourseBerry.Rnw}{rnw}
\end{center}
\end{frame}
\begin{frame}\frametitle{Outline}
\tableofcontents[hideallsubsections]
\label{toc}
\end{frame}
%------------------------------------------------------------%
%------------------------------------------------------------%
\section{Linear models in R}
%------------------------------------------------------------%
%------------------------------------------------------------%
%------------------------------------------------------------%
%------------------------------------------------------------%
\subsection{Linear Regression}
%------------------------------------------------------------%
%------------------------------------------------------------%
% maybe first something on ANOVA
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Linear Regression}
%cite{Crawley2005},
% make note to first slide clickable.
This section (linear models) was originally written by Matthias Seibert (see note on the first slide). I heavily borrowed from his slides and wish to thankfully acknowledge his work!\\[\baselineskip]
Large parts of this section are oriented on \\ (Crawley, 2005) an introductory book on statistics using R, aimed at environmental scientists \\ and (Crawley, 2007) an extensive book on statistics in R. I recommend the book for students who want to learn how to apply statistics in R with little theory.
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Regression types}
\pause
\begin{description}[<+->]
\item[linear regression] the simplest, and the most frequently used
\item[polynomial regression] often used to test for non-linearity in a relationship
\item[piecewise regression] two or more adjacent straight lines
\item[robust regression] models that are less sensitive to outliers
\item[multiple regression] where there are numerous explanatory variables
\item[non-linear regression] to fit a specified non-linear model to data
\item[non-parametric regression] used when there is no obvious functional form
\end{description}
\end{frame}
%------------------------------------------------------------%
%
% <<linreg, include=FALSE>>=
% pdf("./externalfig/linear_regression.pdf", width=5, height=3)
% par(mar=c(2,2,.5,.5))
% plot(1, type="n", xlim=c(0,1), ylim=c(0,1), ylab="", xlab="")
% abline(0.4,0.5, lwd=2)
% dev.off()
% @
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Linear Regression}
The most simple linear model:
\[
y=a+bx
\]
\onslide<2->
\begin{center}
\begin{tabular}{ll}
$y$ & predictand, or response variable\\
$x$ & predictor, or explanatory variable\\
$a$ & intercept\\
$b$ & slope, or gradient\\
\end{tabular}
\onslide<3>
\includegraphics[width=0.5\textwidth]{./externalfig/linear_regression.pdf}
\end{center}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Linear models: Not only linear ...}
\begin{block}{It is not that simple...}
Be aware that with linear models only the parameterisation is linear.\\ The function can also be nonlinear.\\
\( y=ax -bx +cx^2 \) is a linear model\\
\( y=ax_1^2 +b \frac{x_2 + 1}{\sqrt{x_2-1}} +cx_3 *x_4^3 \) is a linear model\\
\end{block}
<<lmex1, out.width="0.3\\textwidth", eval=TRUE>>=
plot(function(x) 1*x -I(2*x) + I(3*x^2), xlim=c(-100, 100))
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Linear Regression}
<<mcregdata>>=
reg.data <- read.table("data/tannin.txt",header=T)
attach(reg.data); names(reg.data)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Linear Regression}
<<mcregdataplot>>=
plot(tannin, growth)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Assumptions and rules of Linear Regression}
\begin{itemize}
\item The variance in y is constant (i.e. does not change as y gets bigger).
\item The explanatory variable, x, is measured without error.
\item The difference between a measured value of y and the value predicted by the model for
the same value of x is called a residual.
\item Residuals are measured on the scale of y (i.e. parallel to the y axis).
\item The residuals are normally distributed
\end{itemize}
\begin{center}
\includegraphics[width=0.4\textwidth]{./externalfig/tannin_residualsplot.png}
\end{center}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Fitting a linear model: specify a formula}
<<lmxy, out.width='.4\\textwidth', fig.height=4, fig.width=4>>=
mod <- lm(growth~tannin)
# visualise the model in a plot
plot(growth~tannin)
# easily done with abline
abline(mod)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Structure of an lm object I}
<<lmstr1, size="scriptsize">>=
str(mod, give.attr=FALSE)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Structure of an lm object II}
<<lmstr2, size="scriptsize">>=
str(mod[1:6])
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Structure of an lm object III}
<<lmstr3, size="footnotesize">>=
str(mod[7:10])
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Structure of an lm object IV}
<<lmstr4, size="scriptsize">>=
str(mod[11])
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Structure of an lm object V}
<<lmstr5, size="scriptsize">>=
str(mod[12])
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Standard output of an lm object}
<<lmprint>>=
mod
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Your turn to practice regression ...}
\begin{exercise}{Explore the methods for lm} %ex12
\begin{enumerate}
\item read and plot the tannin data, fit and plot the linear model
\item Check out the following \rcode{lm} methods:
\begin{enumerate}
\item \rcode{summary()}
\item \rcode{fitted.values}
\item \rcode{residuals}
\item \rcode{anova}
\item \rcode{plot} (click or press enter to continue)
\end{enumerate}
\item Bonus: plot the data, linear model, and add the line parameters into the plot
\end{enumerate}
\end{exercise}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Generic methods for linear model objects}
\begin{description}
\item[print]{standard output, returns formula and estimated coefficients}
\item[summary]{very infomative summary of the fit including statistics}
\item[coefficients]{shows the estimated values for the model coefficients}
\item[fitted.values]{returns the fitted values for the input dataset}
\item[update]{by specifying a formula, you can add or remove parameters from a model}
\item[residuals]{returns the residuals (unexplained variation)}
\item[deviance]{returns the sum of squares of the residuals (RSS)}
\item[anova]{returns an ANOVA table of the results}
\item[lm.influence]{identifies observations of high influence}
\item[predict]{use a model predict from a new dataset}
\item[plot]{diagnostic plot to analyse the quality of fit}
\end{description}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.1}
<<ex11sola, eval=FALSE, size="small">>=
# Data with plant growth and tannin level (a biomolecule)
plants <- read.table("data/tannin.txt", header=TRUE)
str(plants)
attach(plant_data) # Not good practice! confusing scoping!
# attach creates objects of each column in the sub-environment:
ls(pos=2)
detach(plant_data)
# rather use:
plot(growth ~ tannin, data=plants)
# linear model (lm) of growth depending on tannin:
model <- lm(growth ~ tannin, data=plants)
model
abline(model) # adds line to current plot
str(model)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.2}
<<ex11solb, eval=FALSE>>=
summary(model)
# Goodness of fit , coefficient of determination
summary(model)$r.squared # 0.8: pretty good, not perfect
# what values are expected by the model:
fitted.values(model)
points(plants$tannin, fitted.values(model), pch=16, col=2)
# difference between each observation and modeled value:
residuals(model)
# Analysis of Variance (see the statistics books mentioned)
anova(model)
# many plots with statistical information are available:
plot(model)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.3}
<<ex11solc, eval=FALSE>>=
# write Parameters of fit into the graph:
plot(growth ~ tannin, data=plants)
abline(model, col=2)
coef(model)
# y = m*x + b
r <- round( summary(model)$r.squared ,digits=2)
m <- round( coef(model)[2] ,2 )
b <- round( coef(model)[1] ,2 )
Txt <- paste("y =", m, "* x +", b, "\nR^2 =", r)
Txt #\n for line break
text(5,10, Txt, adj=0, col=2)
library(berryFunctions)
linReg(plants$tannin, plants$growth) # for a quick lmplot
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Summary of an lm object}
<<lmsummary, size="scriptsize">>=
oo <- options(width=150)
summary(mod)
@
<<lmsummary2, echo=FALSE>>=
options(oo)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Elements in the summary of a an lm object}
Here is an explanation of the terms in the summary \\[\baselineskip]
\small{
\begin{tabular}{ll}%{rlp{.5\textwidth}}
\texttt{Call:} & the way \rcode{lm} was called\\
\texttt{Residuals:} & descriptive statistics about the residuals\\
\texttt{Coefficients:} & statistical result for the estimated parameters\\
\texttt{- Estimate} & estimated value in the fit\\
\texttt{- Std Error} & standard error of the estimate \\
\texttt{- t value} & t value for the test statistic\\
\texttt{- Pr(\textgreater \textbar t\textbar)} & probability for the estimate to be 0\\
\texttt{Multiple R-squared} & coefficient of determination (explained variation)\\
\texttt{Adjusted R-squared} & adjusted for sample size and number of parameters\\
\texttt{degrees of freedom} & sample size - number of predictors -1\\
% F-statistic & what is this?
\texttt{p-value} & significance of the regression \\
\end{tabular}
}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Coefficient of determination}
The coefficient of determination it a measure of how well a model fits to the data.\\
It shows you the part of variation within the data that is explained by the model.\\
\[R^2 \equiv 1 - \frac{SS_{\rm res}}{SS_{\rm tot}} \]
with\\[\baselineskip]
\begin{tabular}{ll}
\(SS_{tot}=\sum_i (y_i-\bar{y})^2 \) & total sum of squares\\
\(SS_{reg}=\sum_i (f_i -\bar{y})^2 \)& regression (explained) sum of squares\\
\(SS_{res}=\sum_i (y_i - f_i)^2\ \) & sum of squares of residuals\\
\end{tabular} \\[\baselineskip]
Speak: \textit{The model explains XX \% of the variation.}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{$R^2$ is not to be confused with Pearson r (correlation)}
The Pearson product-moment correlation coefficient r (also $\rho$):
\[ r_{xy} = \frac{
\sum_i^n(x_i - \bar{x})(y_i - \bar{y})
}{
\sqrt{\sum_i^n(x_i - \bar{x})^2 \sum_i^n(y_i - \bar{y})^2}}
\]
For the case of a linear model with a single variable $r=\sqrt{R^2}$
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{$R^2$ is not to be confused with Pearson r (correlation)}
For the case of a linear model with a single variable \[r=\sqrt{R^2}\]
<<r2vsr>>=
# Pearson r
cor(tannin, growth)
# R-squared
sqrt(summary(mod)$r.squared)
@
\end{frame}
%------------------------------------------------------------%
%summary
%% measures of fit
%% significance: intercept
%% significance: slope
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Diagnostic plot of an lm object I}
As you saw before, for visualisation of the line you have to add it via \rcode{abline}, the \rcode{plot} function does a diagnostic plot:
%, tidy=T
<<lmdiagplot, eval=F>>=
# allow 4 subplots with par(mfrow=c(2,2))
par(mfrow=c(2,2)); plot(mod)
@
\end{frame}
%------------------------------------------------------------%
%, tidy=T
<<lmdiagploteval, eval=T, include=FALSE, fig.height=6>>=
# allow 4 subplots with par(mfrow=c(2,2))
pdf(file="./externalfig/lmplot.pdf")
par(mfrow=c(2,2)); plot(mod)
dev.off()
@
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Diagnostic plot of an lm object II}
\begin{center}
\includegraphics[width=.6\textwidth]{./externalfig/lmplot.pdf}
\end{center}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Measures of fit}
Corrected sums of squares and sums of products
\begin{description}
\item [y sums of squares] \( SSY=\sum y^2 - \frac{(\sum y)^2}{n}\)
\item [x sums of squares] \( SSX=\sum x^2 - \frac{(\sum x)^2}{n}\)
\item [$x*y$ sums of squares] \( SSXY=\sum xy - \frac{(\sum x)(\sum y)}{n}\)
\end{description}
\end{frame}
%------------------------------------------------------------%
%------------------------------------------------------------%
\subsection{Multivariate linear model}
%------------------------------------------------------------%
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model I}
Before we actually look at multivariate models, let's examine another dataset:
<<tree_examine>>=
class(trees)
head(trees)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model II}
<<tree_height>>=
# Model with just Height:
treemod_vh <- lm(trees$Volume ~ trees$Height)
summary(treemod_vh)$r.squared # 0.3579026
cor(trees$Volume, trees$Height)^2 # 0.3579026 - the same
@
\onslide<2>
<<tree_heightb, eval=FALSE>>=
# low correlation also visible:
plot(trees$Volume ~ trees$Height)
abline(treemod_vh, col=2)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model III}
<<tree_heightc, echo=FALSE, out.width='0.96\\textwidth'>>=
plot(trees$Volume ~ trees$Height)
abline(treemod_vh, col=2)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model IV}
<<tree_heightd>>=
# Just Height, but without intercept
# (we know: Height=0 --> Vol=0)
treemod_vh_noint <- update(treemod_vh, .~. -1)
treemod_vh_noint
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model V}
<<tree_heighte, out.width='0.85\\textwidth'>>=
plot(trees$Volume ~ trees$Height)
abline(treemod_vh, col=2)
abline(treemod_vh_noint, col=4)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model VI}
<<tree_girth, out.width="0.7\\textwidth">>=
# just Girth:
cor(trees$Volume, trees$Girth)^2 # 0.9353199
plot(trees$Girth, trees$Volume, pch=16)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model VII}
To include several predictors, use \rcode{+} in the lm formula.
<<tree_both, size="small">>=
# Both:
treemod_vhg <- lm(Volume ~ Height + Girth, data=trees)
treemod_vhg
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multivariate linear model VIII}
<<tree_both2>>=
# Both:
summary(treemod_vhg)$r.squared
@
Volume prediction from Height not good, from Girth pretty OK.\\
Prediction from both variables not much better than just Girth.
\onslide<2>
<<tree_both3>>=
# Both:
summary(treemod_vhg)$r.squared
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Your turn ...}
\begin{exercise}{multivariate model} %ex13
We measured another tree. The girth is 15 inches and height 70 feet.
\begin{enumerate}
\item Estimate the wood volume by using the \rcode{coef}\texttt{ficients} of the linear model that just uses height as predictor.
\item Estimate it with another regression just using girth.
\item Use the multivariate model to estimate wood volume.
\item What are possibilities and dangers of linear regression models?
\item Bonus: Give uncertainty ranges for the model parameters
\item Bonus: Give uncertainty ranges for the estimates
\end{enumerate}
\end{exercise}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.2-3}
<<ex12sola, eval=TRUE>>=
coef( lm(trees$Volume ~ trees$Girth) )
coef(treemod_vhg)
@
\onslide<2>
<<ex12solb, eval=FALSE>>=
0.339 * 70 + 4.708 * 15 - 57.988 # 36.36
5.066 * 15 - 36.943 # 39.05 cubic feet
@
There is some variation naturally, so we don't know which result is "correct".
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.5-6}
<<ex12solc, eval=TRUE>>=
# prediction confidence interval:
predict(treemod_vhg, newdata=
data.frame(Girth=15, Height=70), interval="conf")
# parameter uncertainty:
confint(treemod_vhg)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.5 II}
<<ex12sold, eval=FALSE>>=
library("berryFunctions") # for addAlpha
plot(Volume~Girth, data=trees, las=1)
mod <- lm(Volume~Girth, data=trees)
x <- 7:22
mod_p <- predict(mod, newdata=data.frame(Girth=x),
interval="conf")
polygon(x=c(x, rev(x)),
y=c(mod_p[,2], rev(mod_p[,3])), col=addAlpha(8))
abline(mod, col=2, lwd=2)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Solution for exercise \arabic{exercisecount}.5 III}
<<ex12sole, echo=FALSE, out.width="1\\textwidth">>=
library("berryFunctions") # for addAlpha
par(mar=c(3, 3, 2, 0), mgp=c(2, 0.7, 0), cex=1.2)
plot(Volume~Girth, data=trees, las=1)
mod <- lm(Volume~Girth, data=trees)
x <- 7:22
mod_p <- predict(mod, newdata=data.frame(Girth=x), interval="conf")
polygon(x=c(x, rev(x)), y=c(mod_p[,2], rev(mod_p[,3])), col=addAlpha(8))
abline(mod, col=2, lwd=2)
@
\end{frame}
%------------------------------------------------------------%
%------------------------------------------------------------%
\subsection{Multiple linear model (ANCOVA)}
%------------------------------------------------------------%
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Multiple linear models (MLM)}
\begin{description}
\item [y sums of squares] \( SSY=\sum y^2 - \frac{(\sum y)^2}{n}\)
\item [x sums of squares] \( SSX=\sum x^2 - \frac{(\sum x)^2}{n}\)
\item [$x*y$ sums of squares] \( SSXY=\sum xy - \frac{(\sum x)(\sum y)}{n}\)
\end{description}
\end{frame}
%------------------------------------------------------------%
% use of glm: some more comfortable features
% %------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example: The ANalysis of COVAriance}
In this example we will look at a special case of the multiple linear model: The ANalysis of COVAriance (ANCOVA).\\[\baselineskip]
You will improve your knowledge about:
\begin{itemize}
\item how to specify a formula
\item how to combine continous and nominally scaled predictors
\item introduction of interaction
\item an alternative plotting environment
\end{itemize}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
Overview of the correlation structure
<<iriscorr>>=
cor(iris[,1:4])
@
We will attempt to set up a model for Sepal.Width
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
Get to know the data: specify a plotting formula
<<irisexpplotexc, include=F>>=
attach(iris)
@
<<irisexpplot, size="small", out.width="0.8\\linewidth">>=
par(mfrow=c(2,2), mar=c(4,4,1,1))
plot(Sepal.Width ~ Sepal.Length + Petal.Length +
Petal.Width + Species, col=Species)
@
<<irisexpplotexc2, include=F>>=
detach(iris)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
For you to take a closer look at: A classical Scatterplot
<<irissplom>>=
library(lattice)
splom(iris)
@
\end{frame}
%------------------------------------------------------------%
% ANCOVA for Sepal.Length ~ Sepal.Length
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
<<irissepwidthplot>>=
# lattice library xyplot for groups highlighting
xyplot(data=iris, Sepal.Width ~ Sepal.Length,
groups=Species, auto.key=T)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset I}
Fitting a linear model using \rcode{glm} since it has some comfortable arguments.\\[\baselineskip]
Both species \textit{Iris versicolor} and \textit{Iris virginica} have a slope significantly different from \textit{Iris setosa}, as can be seen in the next slide:
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset II}
<<optwidth1, echo=FALSE, cache=FALSE>>=
oo <- options(width=150)
@
<<irissepwidthmodel, size="tiny">>=
summary(glm(Sepal.Width ~ Sepal.Length * Species, data=iris))
@
<<optwidth2, echo=FALSE, cache=FALSE>>=
options(oo)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset III}
We remove \textit{Iris setosa} from the plot by introducing a \rcode{subset}.
<<irisswsubsplot>>=
xyplot(data=iris, Sepal.Width ~ Sepal.Length,
groups=Species, auto.key=T, subset=Species!="setosa")
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset IV}
%In the same way we remove \textit{Iris setosa} from the model with a \rcode{subset}.
% , tidy.opts=list(keep.blank.line=FALSE, width.cutoff=60)
<<optwidth3, echo=FALSE, cache=FALSE>>=
oo <- options(width=150)
@
<<irisswsubsmo, size="tiny">>=
summary(glm(Sepal.Width ~ Sepal.Length * Species, data=iris, subset=Species!="setosa"))
@
<<optwidth4, echo=FALSE, cache=FALSE>>=
options(oo)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
Neither the slope nor the intercept of \textit{Iris versiculor} and \textit{Iris virginica} are significantly different. \\
\medskip
For the model we can group them by creating a new factor.
<<irisswmonewfactor>>=
iris$SETOSA <- iris$Species
levels(iris$SETOSA)=c("setosa", "other", "other")
summary(iris$SETOSA)
@
Now we can go back to the full data set and create a model with the new factor: (next slide)
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
% xyplot(data=iris, Sepal.Width ~ Sepal.Length, groups=SETOSA, auto.key=T)
<<optwidth5, echo=FALSE, cache=FALSE>>=
oo <- options(width=150)
@
<<irisswnewmodel, size="tiny">>=
summary(sw.lm <- glm(Sepal.Width ~ Sepal.Length * SETOSA, data=iris))
@
<<optwidth6, echo=FALSE, cache=FALSE>>=
options(oo)
@
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
Plotting using lattice is powerful but takes some time getting used to it.
<<irisswnewmodelplot, eval=F, size="small">>=
xyplot(data=iris, Sepal.Width ~ Sepal.Length, groups=SETOSA,
auto.key=T, col=c("darkslateblue", "tomato2"),
panel=function(x,y,...)
{panel.xyplot(x,y,...)
panel.abline(coef(sw.lm)[1:2],
col="darkslateblue", lwd=2)
panel.abline(coef(sw.lm)[3:4] + coef(sw.lm)[1:2],
col="tomato2", lwd=2)})
@
\end{frame}
%------------------------------------------------------------%
<<irisswnewmodelploteval, include=FALSE>>=
pdf(file="./externalfig/sepalwidth_ancovaplot.pdf", width=7, height=5)
xyplot(data=iris, Sepal.Width ~ Sepal.Length, groups=SETOSA, auto.key=T, col=c("darkslateblue", "tomato2"),
panel=function(x,y,...){panel.xyplot(x,y,...)
panel.abline(coef(sw.lm)[1:2], col="darkslateblue", lwd=2)
panel.abline(coef(sw.lm)[3:4] + coef(sw.lm)[1:2], col="tomato2", lwd=2)})
dev.off()
@
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{MLM example with the iris dataset}
\begin{center}
\includegraphics[width=0.8\textwidth]{./externalfig/sepalwidth_ancovaplot.pdf}
\end{center}
\end{frame}
%------------------------------------------------------------%
\begin{frame}[fragile]\frametitle{Specifying a formula}
\begin{block}{Formula operators used for \rcode{lm}, \rcode{anova}, \rcode{lattice}, ...}
\begin{tabular}{ll}
$\sim$ & ...\\
1 & intercept\\
: & interaction term\\
* & factor crossing, a*b is same as a+b+a:b\\
\^{} & crossing to the specified degree\\
- & removes specified term when updating a model\\
%\%in\% & left term nested within the right: \texttt{a + b \%in\% a} is same as \texttt{a + a:b} \\
\rcode{I}() & operators inside parenthesis are used literally\\
. & used for \rcode{update} of a formula, refers to the existing parameters\\
\textbar & conditional on\\
\end{tabular}
\end{block}