-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMGT6203_Complete.Rmd
1744 lines (1236 loc) · 42.3 KB
/
MGT6203_Complete.Rmd
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
---
title: "MGT6203_Complete"
author: "NathanCook"
date: "August 20, 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# R code used in Module 1
## calling libraries
```{r}
if (!require(Ecdat)) install.packages("Ecdat")
library(Ecdat)
if (!require(ISLR)) install.packages("ISLR")
library(ISLR)
if (!require(GGally)) install.packages("GGally")
library(GGally)
if (!require(car)) install.packages("car")
library(car)
if (!require(psych)) install.packages("psych")
library(psych)
if (!require(MASS)) install.packages("MASS")
library(MASS)
if (!require(tidyverse)) install.packages("tidyverse")
library(tidyverse)
if (!require(stargazer)) install.packages("stargazer")
library(stargazer)
if (!require(knitr)) install.packages("knitr")
library(knitr)
if (!require(stringr)) install.packages("stringr")
library(stringr)
if (!require(ggExtra)) install.packages("ggExtra")
library(ggExtra)
if (!require(scatterplot3d)) install.packages("scatterplot3d")
library(scatterplot3d)
if (!require(faraway)) install.packages("faraway")
library(faraway)
if (!require(broom)) install.packages("broom")
library(broom)
if (!require(lars)) install.packages("lars")
library(lars)
if (!require(scales)) install.packages("scales")
library(scales)
if (!require(ROCR)) install.packages("ROCR")
library(ROCR)
if (!require(boot)) install.packages("boot")
library(boot)
```
## use Housing dataset in the Ecdat package in R
```{r}
?Housing
summary(Housing)
str(Housing)
```
```{r}
head(Housing,10)
```
Not sure where this came in, but it was commented out of original
`table(housing[1:15,],caption='Housing Prices')`
```{r}
h1 <- data.frame(Housing$price, Housing$lotsize, Housing$bedrooms)
head(h1,15)
```
## some useful statistics
```{r}
pp <- Housing$price
pricesd <- sd(pp)
mean(Housing$price)
median(Housing$price)
lot <- Housing$lotsize
lotsd <- sd(lot)
mean(Housing$lotsize)
median(Housing$lotsize)
res <- cor(h1)
round(res,2)
```
Not sure where this came in, but it was commented out of original
`res`
## Plot Histogram of House Prices
```{r}
ggplot(data=Housing, aes(Housing$price)) +
geom_histogram(breaks=seq(25000, 190000, by =10000),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for price") +
labs(x="price", y="Count")
```
## Plot Histogram of Lotsize
```{r}
ggplot(data=Housing, aes(Housing$lotsize)) +
geom_histogram(breaks=seq(0, 17000, by =1000),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for lotsize") +
labs(x="lotsize", y="Count")
```
## Correlation matrix
```{r}
summary(h1)
ggpairs(h1,
upper = list(continuous = wrap("cor", size = 9)))
```
## simple linear regression model with lotsize as predictor
```{r}
a.lm <- lm(formula = price ~ lotsize , data = Housing)
summary(a.lm)
anova(a.lm)
```
## create dataframes called new, new2, and new3
```{r}
new = data.frame(lotsize=3000)
predict(a.lm, new, interval = "predict")
#
new2 = data.frame(lotsize=5150)
predict(a.lm, new2, interval = "predict")
new3 = data.frame(lotsize=7300)
predict(a.lm, new3, interval = "predict")
```
## Scatter Plot of price (y) against lotsize (x), including the linear regression line
```{r}
ggplot(Housing, aes(x=lotsize, y=price)) + geom_point() +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=FALSE, # Don't add shaded confidence region
fullrange=TRUE) # Extend regression lines
```
## simple linear regression model with bedrooms predictor
```{r}
b.lm <- lm(formula = price ~ bedrooms, data = Housing)
```
## Scatter Plot of price (y) against bedrooms (x), including the linear regression line
```{r}
ggplot(Housing, aes(x=bedrooms, y=price)) + geom_point() +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=FALSE, # Don't add shaded confidence region
fullrange=TRUE) # Extend regression lines
```
```{r}
ab.lm <- lm(formula = price ~ lotsize + bedrooms, data = Housing)
summary(ab.lm)
anova(ab.lm)
```
## making a prediction (interpolation)
```{r}
newdata = data.frame(lotsize=3000, bedrooms = 2)
predict(ab.lm, newdata, interval = "predict")
```
# Week 1 Office Hours
```{r}
WD = getwd()
data_path = paste(WD, "/Week01/Dummycsv.csv", sep ="")
data = read.csv(data_path,header = TRUE)
```
```{r}
?ISLR::Hitters
```
```{r}
head(Hitters)
```
```{r}
# Hitters # No reason to see full data frame
```
```{r}
summary(Hitters)
```
```{r}
pairs(Hitters)
```
```{r}
plot(Hitters$AtBat, Hitters$Hits)
```
```{r}
linearModel1 = lm(formula = Salary ~ AtBat + Hits + HmRun, data = Hitters)
summary(linearModel1)
```
```{r}
linearModel = lm(formula = Salary ~., data= Hitters)
linearModel$coefficients
```
```{r}
summary(linearModel)
```
```{r}
plot(linearModel)
```
```{r}
Hitters$League = factor(Hitters$League)
linearModel3 = lm(formula = Salary ~., data= Hitters)
summary(linearModel3)
```
# R code used in Module 2
## do a ggplot histogram plot of price with binsize = 500
```{r}
ggplot(data=Housing, aes(Housing$price)) +
geom_histogram(breaks=seq(1000, 200000, by =500),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for lotsize") +
labs(x="price", y="Count")
```
## do a ggplot histogram plot of price with binsize = 10000
```{r}
ggplot(data=Housing, aes(Housing$price)) +
geom_histogram(breaks=seq(25000, 300000, by =10000),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for price") +
labs(x="price", y="Count")
```
## do a ggplot histogram plot of price with binsize = 50000
```{r}
ggplot(data=Housing, aes(Housing$price)) +
geom_histogram(breaks=seq(25000, 300000, by =50000),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for price") +
labs(x="price", y="Count")
```
## boxplot
```{r}
ggplot(data=Housing, mapping = aes(x = factor(bedrooms), y = price)) +
geom_boxplot() + geom_jitter(width = 0.1)
```
## scatterplot
```{r}
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy)) +
theme(axis.text.x = element_text(size=20), axis.text.y = element_text(size=20),
axis.text=element_text(size=20), axis.title=element_text(size=24,face="bold"))
```
## example 5 from scaterplot3d.f
```{r }
data(trees)
s3d <- scatterplot3d(trees, type="h", highlight.3d=TRUE,
angle=55, scale.y=0.7, pch=16, main="scatterplot3d - 5")
```
## Now adding some points to the "scatterplot3d"
```{r}
s3d <- scatterplot3d(trees, type="h", highlight.3d=TRUE,
angle=55, scale.y=0.7, pch=16, main="scatterplot3d - 5")
s3d$points3d(seq(10,20,2), seq(85,60,-5), seq(60,10,-10),
col="blue", type="h", pch=16)
```
## Now adding a regression plane to the "scatterplot3d"
```{r}
s3d <- scatterplot3d(trees, type="h", highlight.3d=TRUE,
angle=55, scale.y=0.7, pch=16, main="scatterplot3d - 5")
s3d$points3d(seq(10,20,2), seq(85,60,-5), seq(60,10,-10),
col="blue", type="h", pch=16)
attach(trees)
my.lm <- lm(Volume ~ Girth + Height)
s3d$plane3d(my.lm, lty.box = "solid")
```
## correlation matrix
```{r}
h1 <- data.frame(Housing$price, Housing$lotsize, Housing$bedrooms, Housing$bathrms)
ggpairs(h1,
upper = list(continuous = wrap("cor", size = 9)))
```
## Anscombe's Quartet
Four x-y datasets which have the same traditional statistical properties (mean, variance, correlation, regression line, etc.), yet are quite different.
```{r}
anscombe # view the Anscombe dataset
```
## run all four regression models
```{r}
r1 <- lm(y1 ~ x1, data = anscombe)
summary(r1)
r2 <- lm(y2 ~ x2, data = anscombe)
summary(r2)
r3 <- lm(y3 ~ x3, data = anscombe)
summary(r3)
r4 <- lm(y4 ~ x4, data = anscombe)
summary(r4)
```
## plot all four Anscombe models
```{r}
ggplot(anscombe, aes(x=x1, y=y1)) + geom_point((aes(size=3))) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=TRUE, # add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=20), axis.text.y = element_text(size=20),
axis.title=element_text(size=24,face="bold"))
```
```{r}
ggplot(anscombe, aes(x=x2, y=y2)) + geom_point((aes(size=3))) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=TRUE, # add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=20), axis.text.y = element_text(size=20),
axis.title=element_text(size=24,face="bold"))
```
```{r}
ggplot(anscombe, aes(x=x3, y=y3)) + geom_point((aes(size=3))) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=TRUE, # add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=20), axis.text.y = element_text(size=20),
axis.title=element_text(size=24,face="bold"))
```
```{r}
ggplot(anscombe, aes(x=x4, y=y4)) + geom_point(aes(size=3)) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=TRUE, # add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=20), axis.text.y = element_text(size=20),
axis.title=element_text(size=24,face="bold"))
```
## plot the 4 diagnostics plots for a linear model of Price vs. lotsize
```{r}
a.lm <- lm(formula = price ~ lotsize , data = Housing)
plot.new()
plot(a.lm)
par(mfrow = c(2, 2)) # Split the plotting panel into a 2 x 2 grid
plot(a.lm) # Plot # plots the four diagnostics plots
```
## plot residual against fitted (predicted) price
```{r}
plot.new()
a.res <- resid(a.lm)
a.pred <- fitted(a.lm)
plot.new()
plot(a.pred, a.res, main = "Residuals vs. predicted price",
xlab = "Predicted Price", ylab = "Residuals")
```
## ggplot residual against fitted (predicted) price
I didn't want to mess aroung with the built-in dataset Housing. So copy it to a new dataframe df
```{r}
df <- Housing %>% modelr::add_predictions(a.lm) %>% modelr::add_residuals(a.lm)
ggplot(df,aes(x=pred, y=resid)) + geom_point() + labs(x = "Predicted Price") + labs(y = "Residuals") +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
theme(axis.text.x = element_text(size=15), axis.text.y = element_text(size=15),
axis.title=element_text(size=20,face="bold"))
```
## histogram of residuals is useful
Not sure why the abline() is there?
```{r}
# abline(0,0)
hist(a.res, breaks="FD", xlab="Residuals",
main="Histogram of residuals")
```
## Two Regression to illustrate multicollinearity
```{r}
Reg1 <- lm(formula = mpg ~ cylinders, data = Auto)
summary(Reg1)
Reg2 <- lm(formula = mpg ~ cylinders + displacement + weight, data = Auto)
summary(Reg2)
```
## print Variance Inflation factors
```{r}
vif(Reg2)
```
```{r}
h1 <- data.frame(Auto$cylinders, Auto$displacement, Auto$weight)
head(h1,10)
```
```{r}
ggpairs(h1,
upper = list(continuous = wrap("cor", size = 9)))
```
# R Code used in Module 3 (Indicator Variables)
## Use the setwd command to point to your folder where you have saved the EDSAL.csv file
```{r}
WD = getwd()
data_path = paste(WD, "/Week04/EDSAL.csv", sep ="")
```
## edsal is a dataframe to store the contents of the EDAL.csv file
```{r}
edsal <- read_csv(data_path, col_types = list(
Education = readr::col_factor(c("HS", "UG", "GRAD")),
Experience = col_integer(),
Salary = col_double()))
str(edsal) # what happened to the first row of the csv file?
```
```{r}
head(edsal,10)
```
```{r}
contrasts(edsal$Education)
```
## Using the mutate function, to create new variables
## I've creating two new indicator variables called
## Graduate and HS which are determined by the value of Education
## note the use of the pipe operator %>% to add these
## two new variables to edsal
```{r}
edsal<- edsal %>%
mutate(Graduate = ifelse(Education=="GRAD",1,0)) %>%
mutate(HS = ifelse(Education=="HS",1,0))
head(edsal,10)
```
```{r}
ggplot(edsal, aes(x=Experience, y=Salary)) +
geom_point() +
scale_colour_hue(l=50) +
theme(axis.text.x = element_text(size=24),
axis.text.y = element_text(size=24),
axis.text=element_text(size=24),
axis.title=element_text(size=24,face="bold"))
```
```{r}
RS.lm <- lm(Salary ~ Experience, data=edsal)
summary(RS.lm)
```
```{r}
ggplot(edsal, aes(x=Experience, y=Salary)) +
geom_point() +
scale_colour_hue(l=50) +
geom_smooth(method=lm, # Add linear regression lines
se=FALSE, # Don't add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=24),
axis.text.y = element_text(size=24),
axis.text=element_text(size=24),
axis.title=element_text(size=24,face="bold"))
```
```{r}
DR1.lm <- lm(Salary ~ HS + Graduate, data=edsal)
summary(DR1.lm)
```
```{r}
DR2.lm <- lm(Salary ~ Experience + HS + Graduate, data=edsal)
summary(DR2.lm)
```
## adding the INTERACTION VARIBLES to edsal using the mutate function in R
```{r}
edsal<- edsal %>%
mutate(H_Exp = HS*Experience) %>%
mutate(G_Exp = Graduate*Experience)
head(edsal,10)
```
```{r}
DR3.lm <- lm(Salary ~ Experience + HS + Graduate + H_Exp + G_Exp, data=edsal)
summary(DR3.lm)
```
```{r}
ggplot(edsal, aes(x=Experience, y=Salary, color=factor(Education))) +
geom_point(mapping = aes(color=factor(Education))) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=FALSE, # Don't add shaded confidence region
fullrange=TRUE) + # Extend regression lines
theme(axis.text.x = element_text(size=24),
axis.text.y = element_text(size=24),
axis.text=element_text(size=24),
axis.title=element_text(size=24,face="bold"))
```
## AirBnB data
```{r}
data_path = paste(WD, "/Week04/la_listing_full.RData", sep ="")
load(data_path)
```
```{r}
la_listing <- la_listing_full %>%
select(price,
number_of_reviews,
beds,
bathrooms,
accommodates,
reviews_per_month,
property_type,
room_type,
review_scores_rating) %>%
rename(Reviews = number_of_reviews) %>%
rename(Beds = beds) %>%
rename(Baths = bathrooms) %>%
rename(Capacity = accommodates) %>%
rename(Monthly_Reviews = reviews_per_month) %>%
rename(Property_Type = property_type) %>%
rename(Room_Type = room_type) %>%
rename(Price = price) %>%
rename(Rating = review_scores_rating)
la_listing <- la_listing %>%
mutate(Price = str_replace(Price, "[$]", "")) %>%
mutate(Price = str_replace(Price, "[,]", "")) %>%
mutate(Price = as.numeric(Price)) %>%
mutate(Room_Type = factor(Room_Type,
levels = c("Shared room",
"Private room",
"Entire home/apt"))) %>%
mutate(Capacity_Sqr = Capacity * Capacity) %>%
mutate(Beds_Sqr = Beds * Beds) %>%
mutate(Baths_Sqr = Baths * Baths) %>%
mutate(ln_Price = log(1+Price)) %>%
mutate(ln_Beds = log(1+Beds)) %>%
mutate(ln_Baths = log(1+Baths)) %>%
mutate(ln_Capacity = log(1+Capacity)) %>%
mutate(ln_Rating = log(1+Rating)) %>%
mutate(Shared_ind = ifelse(Room_Type == "Shared room",1,0)) %>%
mutate(House_ind = ifelse(Room_Type == "Entire home/apt",1,0)) %>%
mutate(Private_ind = ifelse(Room_Type == "Private room",1,0)) %>%
mutate(Capacity_x_Shared_ind = Shared_ind * Capacity) %>%
mutate(H_Cap = House_ind * Capacity) %>%
mutate(P_Cap = Private_ind * Capacity) %>%
mutate(ln_Capacity_x_Shared_ind = Shared_ind * ln_Capacity) %>%
mutate(ln_Capacity_x_House_ind = House_ind * ln_Capacity) %>%
mutate(ln_Capacity_x_Private_ind = Private_ind * ln_Capacity)
la_listing <- la_listing %>%
dplyr::filter(Price < 1000 ,
!is.na(Beds),
!is.na(Baths),
!is.na(Price),
!is.na(Rating)) %>%
dplyr::filter(Capacity < 9) %>%
mutate(ln_Reviews = log(1+Reviews)) %>%
mutate(ln_Monthly_Reviews = log(1+Monthly_Reviews))
```
## We can examine if the number of people a listing can accomodate is related to price.
```{r}
lm0 <- lm(Price ~ Capacity, data = la_listing)
summary(lm0)
```
```{r}
stargazer(lm0, type = "text")
```
```{r}
ggplot(data = la_listing, aes(x = Capacity, y = Price)) +
geom_point(size=3) +
scale_colour_hue(l=50) + # Use a slightly darker palette than normal
geom_smooth(method=lm, # Add linear regression lines
se=TRUE, # add shaded confidence region
fullrange=TRUE) +
theme(axis.text.x = element_text(size=24),
axis.text.y = element_text(size=24),
axis.title=element_text(size=24,face="bold"))
```
## The moderating effect of type of room. Lets model that.
```{r}
lm1 <- lm(Price ~ Private_ind + House_ind, data = la_listing)
summary(lm1)
```
```{r}
stargazer(lm1, type = "text")
```
## Regression with Capacity and Dummy Variables for type of room:
```{r}
lm2 <- lm(Price ~ Capacity + Private_ind + House_ind, data = la_listing)
summary(lm2)
```
```{r}
stargazer(lm2, type = "text")
```
## Regression with Capacity,Dummy Variables and interaction between the two:
```{r}
lm3 <- lm(Price ~ Capacity+Private_ind + House_ind+P_Cap+H_Cap, data = la_listing)
summary(lm3)
```
```{r}
stargazer(lm3,type = "text")
```
# Office Hours for Week 3
```{r}
data("prostate")
help(prostate)
```
## Understanding the data
```{r}
head(prostate)
```
```{r}
nrow(prostate)
```
```{r}
ncol(prostate)
```
## EXAMPLE OF BACKWARD ELIMINATION
### Lm with all variables
```{r}
lmod1 = lm(lpsa ~ ., data = prostate)
summary(lmod1)
```
```{r}
lmod1 <- update(lmod1,. ~. -gleason)
summary(lmod1)
```
```{r}
lmod1 <- update(lmod1,. ~. -lcp)
summary(lmod1)
```
```{r}
lmod1 <- update(lmod1,. ~. -pgg45)
summary(lmod1)
```
```{r}
lmod1 <- update(lmod1,. ~. -age)
summary(lmod1)
```
## STEPWISE
```{r}
data(fat)
head(fat)
```
```{r}
sample = seq(10,250, by = 10)
testData = fat[sample, -c(1,3)]
trainingData = fat[-sample, -c(1,3)]
```
### Step documentation
```{r}
help("step")
```
```{r}
lmodA = lm(siri ~., data=trainingData)
summary(lmodA)
```
```{r}
lmodB = step(lmodA, trace=0)
summary(lmodB)
```
## RMSE function
```{r}
rmse = function(x,y){
sqrt(mean((x-y)^2))
}
```
### Getting error values, RMSE
```{r}
rmse_out <- rmse(lmodB$fitted.values, trainingData)
```
### prediction using lmodB on test data
```{r}
predictionB = predict(lmodB, testData)
```
### How good is your prediction
```{r}
rmse_outB <- rmse(predictionB, testData$siri) #rmse = 1.122
```
## Ridge regression
```{r}
rigmod = lm.ridge(siri ~., data=trainingData, lambda=seq(0,10,0.01))
summary(rigmod)
```
### below shows you values of lambda vs gcv
```{r}
td = tidy(rigmod)
g = glance(rigmod)
```
### plot of GCV versus lambda
```{r}
ggplot(td, aes(lambda, GCV)) +
geom_line() +
geom_vline(xintercept = g$lambdaGCV,
col = "red",
lty = 2)
```
### below helps select a good tuning parameter lambda
```{r}
matplot(rigmod$lambda, t(rigmod$coef),
type = "l",
xlab = expression(lambda),
ylab=expression(hat(beta)))
```
```{r}
which.min(rigmod$GCV) #good tuning parameter => lambda = 0.05 at the 6th data point
```
### now do prediction on your model using test data
```{r}
ypredTest = cbind(1, as.matrix(testData[,-1])) %*% coef(rigmod)[6,]
rmse_ypredTest <- rmse(ypredTest, testData$siri) #rmse = 1.13
```
## lasso regression
```{r}
trainx = as.matrix(trainingData[-1])
trainy = trainingData$siri
help(lars)
lassomodel = lars(trainx, trainy)
summary(lassomodel)
```
```{r}
plot(lassomodel)
```
### compute the crossvalidation choice for t:
```{r}
set.seed(123)
cvmod = cv.lars(trainx, trainy)
```
```{r}
cvmod$index[which.min(cvmod$cv)] #min error = 0.788
```
Keep in mind, that we first compute the parameters of the model (lambda or s in lasso case)
Then we use parameters for a predition
We rate model based on error(RMSE) values -> you can compare different models this way
```{r}
testx = as.matrix(testData[-1])
predlarsTest = predict(lassomodel, testx, s = 0.788, mode = "fraction")
rmse_predlars <- rmse(testData$siri, predlarsTest$fit) #rmse = 1.112
```
Summary of 3 models
Stepwise, rmse = 1.122