-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_main.Rmd
1838 lines (1255 loc) · 89.6 KB
/
_main.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: "Derek Corcoran"
---
Website of Derek Corcoran Data Scientist
```{r, echo=FALSE}
knitr::include_graphics('GSTxF.jpg')
```
Derek was born in Punta Arenas, the southernmost city of Chile, in 1981. He studied Biological Sciences at Concepción University of Chile and obtained his bachelor degree at 2006. During 2008, he began a PhD in Ecology at Catholic University of Chile. In 2010, he came back to Punta Arenas to develop his PhD research about the [North American beaver invasion](https://cienciaustral.com/nuestro-trabajo-cientifico/research/invasion-castor-norteamericano-en-patagonia/). Studying beaver’s distribution modeling, he started to develop his quantitative skills within the R software environment.
Then in 2015, during a Postdoctoral position in the University of Missouri, he investigated the occupancy of 12 bat species in the Sierra Nevada and which variables better explained their occupancy. Both experimental design and data analysis, allowed him to implement new systems of quantitative analysis, creating an R package called [*DiversityOcupancy*](http://rpubs.com/derek_corcoran/DiversityOccupancy). At the same time, through collaborations he started his research in quantitative analysis in sport, which allowed him to create a [basketball spatial model](https://derek-corcoran-barrios.github.io/about.html) considering the pairwise comparison of teams offensive and defensive spatial configuration and performance.
Today, he is working at Catholic University of Chile in his second postdoctoral position. He is part of two projects which try to establish a model of maximization of conservation of species [considering climate change](http://www.sparc-website.org/) while minimizing the land required to incorporate to the global network of protected area using network flow optimization and collaborating with mathematicians. Equally important, he has been teaching [R courses](https://derek-corcoran-barrios.github.io/CursoR.html) for PhD students in the same University, looking forward to build up new modules for teaching R for researchers and develop an online course of R with the Postgraduate Department.
Derek is the co-founder of [Ciencia Austral](https://cienciaustral.com/), an environmental consultancy based in Punta Arenas focused in scientific advisory and education. Here, he has worked in projects about beaver eradication, sustainable harvesting of guanacos, ecosystem services of dung beetles, and data science, learning not only R, but also Python and AMPL.
<!--chapter:end:index.Rmd-->
---
title: "Project description"
---
We have created this site to share the results of our spatial analysis of the game of basketball with the public. The general concept behind this research project was to build a predictive model for the outcome of National Basketball Association (NBA) games based on the offensive and defensive matchup between teams. In order to do this, we examined around one million shots (about five years of data) by pairing up the offensive and defensive shot charts for every team in the NBA against all other opponents. From this, we have managed to build a machine learning algorithm which can be used for analysis such as:
- Predicting the spread for [every NBA game](https://derek-corcoran-barrios.github.io/Projection.html).
- Estimating the impact that trades have on expected outcome and performance for teams
- Spatially analyzing the locations where teams perform well on offense and defense using [shot charts](https://derek-corcoran-barrios.github.io/ShotCharts.html).
- Calculating our own [spatial power rankings](https://derek-corcoran-barrios.github.io/Rating.html) and [team stats](https://derek-corcoran-barrios.github.io/TeamStats.html)
- Finding key points where teams are able to improve matchups against other teams
- And much much more… From all of this, we hope to show how using spatial analysis can provide more critical insights into the nature of NBA games.
<!--chapter:end:about.Rmd-->
---
title: "BlogHome"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, cache = TRUE, warning = FALSE, message = FALSE)
```
## [Does the recent Bulls winning streak mean something?](https://derek-corcoran-barrios.github.io/Mirotic)
*December 20th, 2017*
```{r}
library(dplyr)
library(lubridate)
library(SpatialBall2)
library(gridExtra)
library(ggplot2)
Season2018 <- readRDS("Season2018.rds")
NM <- filter(Season2018, GAME_DATE >= dmy("8/12/2017"))
WONM <- filter(Season2018, GAME_DATE < dmy("8/12/2017"))
```
### Shot charts with and without Nikola Mirotic
Since Nikola, has just played 6 games, there's too few shots to make a passable shot chart of Chicago with him, so we will have to rely on team stats to figure what is going on.
```{r, fig.width=6, fig.height=12}
Without <- OffShotSeasonGraphTeam(Seasondata = WONM, team = "Chi") + ggtitle("Offensive without Mirotic")
With <- OffShotSeasonGraphTeam(Seasondata = NM, team = "Chi", quant = 0.05)+ ggtitle("Offensive with Mirotic")
grid.arrange(Without, With, ncol = 1)
```
[Read more...](https://derek-corcoran-barrios.github.io/Mirotic)
## [The first team ever to shoot more than half their shots beyond the three point line](https://derek-corcoran-barrios.github.io/Blog)
*December 2nd, 2017*
For while we`ve been wondering if there is such a thing as too many three pointers for a team. Well we can keep asking ourselves that, as today December the second of 2017, The Rockets are shooting an NBA all-time record 53% of their shots from three point range, followed by last season's Rockets with 46%. Third place is held by last year’s Cavs team, with 40%, a 13% difference. And it's not even close to the second, just compare this years Rockets shot chart with 2001 NBA Champions LA Lakers, it's a completely different sport!
```{r}
knitr::include_graphics("https://derek-corcoran-barrios.github.io/Blog_files/figure-html/unnamed-chunk-3-1.png")
```
[Read more...](https://derek-corcoran-barrios.github.io/Blog)
<!--chapter:end:BlogHome.Rmd-->
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = TRUE)
```
```{r load packs}
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, DT, stringr, purrr, dplyr, ggplot2, plotly)
```
```{r getting stats, echo=FALSE}
Season2018 <- readRDS("Season2018.rds")
TeamStats2018 <- Season2018 %>% mutate(EVENT_TYPE = make.names(EVENT_TYPE), SHOT_TYPE = str_replace(SHOT_TYPE, " Field Goal", "")) %>% group_by(TEAM_NAME, SHOT_TYPE, EVENT_TYPE) %>% dplyr::summarise(N = n()) %>% spread(key = EVENT_TYPE, value = N) %>% split(.$SHOT_TYPE) %>% map(~mutate(.x, ShotPct = round(Made.Shot/(Made.Shot +Missed.Shot), 3), Total = Made.Shot + Missed.Shot))
Points <- c("2Pts", "3Pts")
for(i in 1:length(TeamStats2018)){
colnames(TeamStats2018[[i]])[2:6] <- paste0(colnames(TeamStats2018[[i]])[2:6], Points[i])
}
TeamStats2018 <- TeamStats2018 %>% reduce(merge) %>% select(-SHOT_TYPE2Pts, -SHOT_TYPE3Pts, -Made.Shot2Pts, -Made.Shot3Pts, -Missed.Shot2Pts, -Missed.Shot3Pts) %>% mutate(TotalShots = Total2Pts + Total3Pts) %>% mutate(PercentageOf2s = round(Total2Pts/TotalShots,2),PercentageOf3s = round(Total3Pts/TotalShots, 2)) %>% select(-TotalShots, -Total2Pts, -Total3Pts)
Teams <- unique(Season2018$TEAM_NAME)
Prop <- data.frame(TEAM_NAME = Teams , PropShot = NA)
for(i in 1:30){
Offa <- dplyr::filter(Season2018, HTM == Teams[i] | VTM == Teams[i])
Prop$PropShot[i] <- round(nrow(dplyr::filter(Offa, TEAM_NAME == Teams[i]))/nrow(dplyr::filter(Offa,TEAM_NAME != Teams[i])),3)
}
TeamStats2018 <- full_join(TeamStats2018, Prop) %>% mutate(PPS = round((ShotPct2Pts*2*PercentageOf2s)+(ShotPct3Pts*3*PercentageOf3s),3)) %>% mutate(AdjPPS = round((PPS * PropShot),3)) %>% mutate(Season = 2018)
```
```{r MakeTable, echo=FALSE}
TeamStats2018 <- TeamStats2018
```
```{r, cache = TRUE}
pacman::p_load(tidyverse, DT, stringr, purrr, dplyr)
library(SpatialBall2)
Season2001 <- readRDS("Season2001.rds")
TeamStats2001 <- Season2001 %>% mutate(EVENT_TYPE = make.names(EVENT_TYPE), SHOT_TYPE = str_replace(SHOT_TYPE, " Field Goal", "")) %>% group_by(TEAM_NAME, SHOT_TYPE, EVENT_TYPE) %>% dplyr::summarise(N = n()) %>% spread(key = EVENT_TYPE, value = N) %>% split(.$SHOT_TYPE) %>% map(~mutate(.x, ShotPct = round(Made.Shot/(Made.Shot +Missed.Shot), 3), Total = Made.Shot + Missed.Shot))
Points <- c("2Pts", "3Pts")
for(i in 1:length(TeamStats2001)){
colnames(TeamStats2001[[i]])[2:6] <- paste0(colnames(TeamStats2001[[i]])[2:6], Points[i])
}
TeamStats2001 <- TeamStats2001 %>% reduce(merge) %>% select(-SHOT_TYPE2Pts, -SHOT_TYPE3Pts, -Made.Shot2Pts, -Made.Shot3Pts, -Missed.Shot2Pts, -Missed.Shot3Pts) %>% mutate(TotalShots = Total2Pts + Total3Pts) %>% mutate(PercentageOf2s = round(Total2Pts/TotalShots,2),PercentageOf3s = round(Total3Pts/TotalShots, 2)) %>% select(-TotalShots, -Total2Pts, -Total3Pts)
Teams <- unique(Season2001$TEAM_NAME)
Prop <- data.frame(TEAM_NAME = Teams , PropShot = NA)
for(i in 1:length(Teams)){
Offa <- dplyr::filter(Season2001, HTM == Teams[i] | VTM == Teams[i])
Prop$PropShot[i] <- round(nrow(dplyr::filter(Offa, TEAM_NAME == Teams[i]))/nrow(dplyr::filter(Offa,TEAM_NAME != Teams[i])),3)
}
TeamStats2001 <- full_join(TeamStats2001, Prop) %>% mutate(PPS = round((ShotPct2Pts*2*PercentageOf2s)+(ShotPct3Pts*3*PercentageOf3s),3)) %>% mutate(AdjPPS = round((PPS * PropShot),3)) %>% mutate(Season = 2001)
TeamStats2001 <- TeamStats2001
data("season2017")
Season2017 <- season2017
TeamStats2017 <- Season2017 %>% mutate(EVENT_TYPE = make.names(EVENT_TYPE), SHOT_TYPE = str_replace(SHOT_TYPE, " Field Goal", "")) %>% group_by(TEAM_NAME, SHOT_TYPE, EVENT_TYPE) %>% dplyr::summarise(N = n()) %>% spread(key = EVENT_TYPE, value = N) %>% split(.$SHOT_TYPE) %>% map(~mutate(.x, ShotPct = round(Made.Shot/(Made.Shot +Missed.Shot), 3), Total = Made.Shot + Missed.Shot))
Points <- c("2Pts", "3Pts")
for(i in 1:length(TeamStats2017)){
colnames(TeamStats2017[[i]])[2:6] <- paste0(colnames(TeamStats2017[[i]])[2:6], Points[i])
}
TeamStats2017 <- TeamStats2017 %>% reduce(merge) %>% select(-SHOT_TYPE2Pts, -SHOT_TYPE3Pts, -Made.Shot2Pts, -Made.Shot3Pts, -Missed.Shot2Pts, -Missed.Shot3Pts) %>% mutate(TotalShots = Total2Pts + Total3Pts) %>% mutate(PercentageOf2s = round(Total2Pts/TotalShots,2),PercentageOf3s = round(Total3Pts/TotalShots, 2)) %>% select(-TotalShots, -Total2Pts, -Total3Pts)
Teams <- unique(Season2017$TEAM_NAME)
Prop <- data.frame(TEAM_NAME = Teams , PropShot = NA)
for(i in 1:length(Teams)){
Offa <- dplyr::filter(Season2017, HTM == Teams[i] | VTM == Teams[i])
Prop$PropShot[i] <- round(nrow(dplyr::filter(Offa, TEAM_NAME == Teams[i]))/nrow(dplyr::filter(Offa,TEAM_NAME != Teams[i])),3)
}
TeamStats2017 <- full_join(TeamStats2017, Prop) %>% mutate(PPS = round((ShotPct2Pts*2*PercentageOf2s)+(ShotPct3Pts*3*PercentageOf3s),3)) %>% mutate(AdjPPS = round((PPS * PropShot),3)) %>% mutate(Season = 2017)
TeamStats2017 <- TeamStats2017
pacman::p_load(tidyverse, DT, stringr, purrr, dplyr)
Season2016 <- readRDS("shotDataTotal2016.rds")
TeamStats2016 <- Season2016 %>% mutate(EVENT_TYPE = make.names(EVENT_TYPE), SHOT_TYPE = str_replace(SHOT_TYPE, " Field Goal", "")) %>% group_by(TEAM_NAME, SHOT_TYPE, EVENT_TYPE) %>% dplyr::summarise(N = n()) %>% spread(key = EVENT_TYPE, value = N) %>% split(.$SHOT_TYPE) %>% map(~mutate(.x, ShotPct = round(Made.Shot/(Made.Shot +Missed.Shot), 3), Total = Made.Shot + Missed.Shot))
Points <- c("2Pts", "3Pts")
for(i in 1:length(TeamStats2016)){
colnames(TeamStats2016[[i]])[2:6] <- paste0(colnames(TeamStats2016[[i]])[2:6], Points[i])
}
TeamStats2016 <- TeamStats2016 %>% reduce(merge) %>% select(-SHOT_TYPE2Pts, -SHOT_TYPE3Pts, -Made.Shot2Pts, -Made.Shot3Pts, -Missed.Shot2Pts, -Missed.Shot3Pts) %>% mutate(TotalShots = Total2Pts + Total3Pts) %>% mutate(PercentageOf2s = round(Total2Pts/TotalShots,2),PercentageOf3s = round(Total3Pts/TotalShots, 2)) %>% select(-TotalShots, -Total2Pts, -Total3Pts)
Teams <- unique(Season2016$TEAM_NAME)
Prop <- data.frame(TEAM_NAME = Teams , PropShot = NA)
for(i in 1:length(Teams)){
Offa <- dplyr::filter(Season2016, HTM == Teams[i] | VTM == Teams[i])
Prop$PropShot[i] <- round(nrow(dplyr::filter(Offa, TEAM_NAME == Teams[i]))/nrow(dplyr::filter(Offa,TEAM_NAME != Teams[i])),3)
}
TeamStats2016 <- full_join(TeamStats2016, Prop) %>% mutate(PPS = round((ShotPct2Pts*2*PercentageOf2s)+(ShotPct3Pts*3*PercentageOf3s),3)) %>% mutate(AdjPPS = round((PPS * PropShot),3))%>% mutate(Season = 2016)
TeamStats2016 <- TeamStats2016
pacman::p_load(tidyverse, DT, stringr, purrr, dplyr)
Season2015 <- readRDS("shotDataTotal2015.rds")
TeamStats2015 <- Season2015 %>% mutate(EVENT_TYPE = make.names(EVENT_TYPE), SHOT_TYPE = str_replace(SHOT_TYPE, " Field Goal", "")) %>% group_by(TEAM_NAME, SHOT_TYPE, EVENT_TYPE) %>% dplyr::summarise(N = n()) %>% spread(key = EVENT_TYPE, value = N) %>% split(.$SHOT_TYPE) %>% map(~mutate(.x, ShotPct = round(Made.Shot/(Made.Shot +Missed.Shot), 3), Total = Made.Shot + Missed.Shot))
Points <- c("2Pts", "3Pts")
for(i in 1:length(TeamStats2015)){
colnames(TeamStats2015[[i]])[2:6] <- paste0(colnames(TeamStats2015[[i]])[2:6], Points[i])
}
TeamStats2015 <- TeamStats2015 %>% reduce(merge) %>% select(-SHOT_TYPE2Pts, -SHOT_TYPE3Pts, -Made.Shot2Pts, -Made.Shot3Pts, -Missed.Shot2Pts, -Missed.Shot3Pts) %>% mutate(TotalShots = Total2Pts + Total3Pts) %>% mutate(PercentageOf2s = round(Total2Pts/TotalShots,2),PercentageOf3s = round(Total3Pts/TotalShots, 2)) %>% select(-TotalShots, -Total2Pts, -Total3Pts)
Teams <- unique(Season2015$TEAM_NAME)
Prop <- data.frame(TEAM_NAME = Teams , PropShot = NA)
for(i in 1:length(Teams)){
Offa <- dplyr::filter(Season2015, HTM == Teams[i] | VTM == Teams[i])
Prop$PropShot[i] <- round(nrow(dplyr::filter(Offa, TEAM_NAME == Teams[i]))/nrow(dplyr::filter(Offa,TEAM_NAME != Teams[i])),3)
}
TeamStats2015 <- full_join(TeamStats2015, Prop) %>% mutate(PPS = round((ShotPct2Pts*2*PercentageOf2s)+(ShotPct3Pts*3*PercentageOf3s),3)) %>% mutate(AdjPPS = round((PPS * PropShot),3))%>% mutate(Season = 2015)
TeamStats2015 <- TeamStats2015
```
```{r}
library(plotly)
TeamStats <- rbind(TeamStats2001, TeamStats2018)
TeamStats <- rbind(TeamStats, TeamStats2017)
TeamStats <- rbind(TeamStats, TeamStats2016)
TeamStats <- rbind(TeamStats, TeamStats2015)
TeamStats <- arrange(TeamStats, desc(PercentageOf3s))
p <- ggplot(TeamStats, aes(x = PercentageOf3s, y = PPS)) + geom_point() + geom_smooth(method = "lm") + ggtitle("Figure 1") + geom_text(aes(label=TEAM_NAME),hjust=0, vjust=0) + xlab("Proportion of shots that are 3pts")
```
## The first team ever to shoot more than half their shots beyond the three point line
For while we`ve been wondering if there is such a thing as too many three pointers for a team. Well we can keep asking ourselves that, as today December the second of 2017, The Rockets are shooting an NBA all-time record 53% of their shots from three point range, followed by last season's Rockets with 46%. Third place is held by last year’s Cavs team, with 40%, a 13% difference. And it's not even close to the second, just compare this years Rockets shot chart with 2001 NBA Champions LA Lakers, it's a completely different sport!
```{r}
library(SpatialBall)
library(gridExtra)
a <- SpatialBall::OffShotSeasonGraphTeam(Seasondata = Season2018, team = "Hou")
b <- SpatialBall::OffShotSeasonGraphTeam(Seasondata = Season2001, team = "Lal")
grid.arrange(a,b, ncol =2)
```
In the plot and table bellow we can see that this year the Rockets are shooting `r TeamStats$PercentageOf3s[1]*100` % of their shots from the three point range, followed by the same team of last year. The third place, is last year's Cavs team, with `r TeamStats$PercentageOf3s[3]*100` %, that is a `r TeamStats$PercentageOf3s[1]*100 -TeamStats$PercentageOf3s[3]*100`% difference!!
### Why keep jacking up threes?
Does this make any sense? As we see in figure 1, there is a positive relationship between the percentage of shots a team takes that are three pointers with their points per shot. Actually, if we don't count the Golden State Warriors teams from 2016, 2017 and this year incarnation of the team, this year Rockets team has the highest Point per shot mark in the last 5 years at `r TeamStats$PPS[1]`, while making only `r TeamStats$ShotPct3Pts[1]*100`% of them.
```{r}
ggplotly(p)
```
### What would happend if the warriors shot as many threes as the Rockets
As told above, this year warriors are the top team in the last 5 years in Points per shot making `r dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$PPS` points per shot. They are making an efficient `r dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$ShotPct3Pts*100`% of their three pointers and an outstanding `r dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$ShotPct2Pts*100`% of their two pointers. But what would happen if they shot they same proportion of their shots form the three point line as the Rockets did?
Well, they would change their PPS to `r round((dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$ShotPct3Pts*3*dplyr::filter(TeamStats, TEAM_NAME == "Hou" & Season == 2018)$PercentageOf3s) + (dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$ShotPct2Pts*2*dplyr::filter(TeamStats, TEAM_NAME == "Hou" & Season == 2018)$PercentageOf2s),3)` which is an increment, but no by so much.
```{r}
DT::datatable(TeamStats)
```
### Is there any downsides on shooting this many three pointers?
If we look at the proportion of shots a team takes as a proportion of the number of shots their opponent takes as shown in the formula bellow, we see in the following graph (figure 2) that the more threes you take, the less proportions of shots you take. The other team gets more second chances, but the slope of that tendency is a lot lower than the one in Figure 1. That is, usually the proportion of shots you loose by taking more threes is more than offset by the increase in points per shots.
$$PropShot =\frac{ShotsTaken_{Offense}}{ShotsAllowed_{Defense}}$$
On the other hand, it can still change the outcome of a match. If you see in this years [team stats](https://derek-corcoran-barrios.github.io/TeamStats.html), you will see that even when Golden State has the higher Points per shot in the NBA, it only takes `r dplyr::filter(TeamStats, TEAM_NAME == "GSW" & Season == 2018)$PropShot` shots per every opponent shot. That is why we added the column AdjPPS, which is basically the Points per shot you take adjusted by the proportion of shots taken in a match.
```{r}
prop <- ggplot(TeamStats, aes(x = PropShot, y = PercentageOf3s)) + geom_point() + geom_smooth(method = "lm") + ggtitle("Figure 2") + geom_text(aes(label=TEAM_NAME),hjust=0, vjust=0) + xlab("Shots taken/shots taken by opponent") + ylab("Proportion of shots that are 3pts")
ggplotly(prop)
```
<!--chapter:end:Blog.Rmd-->
---
title: "Curso de R"
author: "Derek Corcoran"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# BIO 4022. Análisis y manipulación de datos en R
### En el inicio se encuentra:
- Read me file, explicación del contenido de este repositorio
- El pdf con el temario y evaluación del curso
### En la carpeta de cada clase se encuentra:
- el archivo Rpres y HTML correspondiente a cada clase
- Los datos, figuras o links utilizados para cada clase
# Links a las Clases en html
- Antes de empezar, si no has utilizado R anteriormente por favor revisa este
[Video](https://youtu.be/w6L7Ye18yPE) y realiza las primeras 7 lecciones de
*R Programming* en Swirl
- [Clase 1](https://derek-corcoran-barrios.github.io/Clase1/Clase1TidyData)
- [Clase 2](http://rpubs.com/derek_corcoran/Clase2). También puedes ver el video de la clase.
<iframe width="560" height="315" src="https://www.youtube.com/embed/Ft6r7pD_eSs" frameborder="0" allowfullscreen></iframe>
- [Clase 3](http://rpubs.com/derek_corcoran/Clase3). También puedes ver el video de la clase.
+ Video que muestra como [realizar](https://youtu.be/lDp5OJzeG34) el ejercicio 3 de la clase.
<iframe width="560" height="315" src="https://www.youtube.com/embed/5tjCeFb2oSk" frameborder="0" allowfullscreen></iframe>
- [Clase 4](http://rpubs.com/derek_corcoran/Clase4). También puedes ver el [video](https://youtu.be/miqDWpVEMRg) de la clase.
- [Clase 5](http://rpubs.com/derek_corcoran/Clase5). También puedes ver el [video](https://youtu.be/bvzi88XRq4c) de la clase.
- [Clase 6](http://rpubs.com/derek_corcoran/Clase6). También puedes ver el [video](https://youtu.be/nGb2__ksaho) de la clase.
- [Clase 7](http://rpubs.com/derek_corcoran/Clase7). También puedes ver el [video](https://youtu.be/_deboekuWt0) de la clase.
# Evaluaciones
* Pueden ver en este [link](http://rpubs.com/derek_corcoran/NotasBIO4022_2_2017) la evaluación de la primera tarea.
* En este [link](http://rpubs.com/derek_corcoran/Eval2) pueden ver la evaluación de la segunda tarea
* Finalmente en este [link](http://rpubs.com/derek_corcoran/NotasBIO4022_2_final2017) se encuentran las notas finales.
<!--chapter:end:CursoR.Rmd-->
---
title: "Donde vivir"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<iframe src="https://derek-corcoran.shinyapps.io/WhereShouldYouLive/?showcase=0" width="1000" height="1600px">
</iframe>
<!--chapter:end:DondeVivir.Rmd-->
---
title: "Sismos en Chile"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(warning=FALSE)
```
```{r, message=FALSE, echo=FALSE, warning=FALSE}
if (!require("pacman")) install.packages("pacman")
pacman::p_load(ggmap, ggplot2, dplyr, readr, leaflet, dygraphs, xts, lubridate, geojsonio, stringr)
```
```{r, echo=FALSE, warning=FALSE, cache=FALSE}
Earthquakes <- read_csv("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.csv")
Earthquakes$time <- lubridate::with_tz(Earthquakes$time, tz = "America/Santiago")
Chile <- as.data.frame(dplyr::filter(Earthquakes, latitude < -17 & latitude > -60 & longitude < -65 & longitude > -75))
Last <- max(dplyr::filter(Chile, mag >= ifelse(max(Chile$mag) < 6,max(Chile$mag), 6))$time)
```
Desde el `r strftime(min(Earthquakes$time), format="%d-%m-%Y", usetz = FALSE)` al `r strftime(max(Earthquakes$time), format="%d-%m-%Y", usetz = FALSE)`, han habido `r NROW(dplyr::filter(Chile, mag >= ifelse(max(Chile$mag) < 6,max(Chile$mag), 6)))` sismos sobre magnitud `r ifelse(max(Chile$mag) < 6,max(Chile$mag), 6)` en Chile y sus cercanias. Estos han ocurrido en las localidades de `r str_replace(str_replace(dplyr::filter(Chile, mag >= ifelse(max(Chile$mag) < 6,max(Chile$mag), 6))$place, "km", " kms al"), "of", "de")`.
El temblor sobre grado `r ifelse(max(Chile$mag) < 6,max(Chile$mag), 6)`, mas reciente ocurrio en `r strftime(max(dplyr::filter(Chile, mag >= ifelse(max(Chile$mag) < 6,max(Chile$mag), 6))$time), format="%d-%m-%Y", usetz = FALSE)`, y desde esa fecha han ocurrido un total de `r nrow(dplyr::filter(Chile, time >= Last))` sismos.
En el siguiente mapa interactivo, se ven todos los temblores del último año, en este se encuentran en rojo, todos los temblores con una magnitud sobre 6 en la escala de richter y en azul bajo 6. Si te posas sobre cada circulo te mostrará la magnitud de este temblor, y si haces click sobre un circulo, aparecerá el día y hora en que este temblor ocurrio.
```{r, message=FALSE, echo=FALSE, warning=FALSE, fig.cap= "Sismos ocurridos en el mundo en los últimos 30 días con magnitud sobre 2.5 (Datos extraidos de USGS))"}
plaques <- geojsonio::geojson_read("https://raw.githubusercontent.com/fraxen/tectonicplates/master/GeoJSON/PB2002_boundaries.json", what = "sp")
MAG <- as.numeric(Earthquakes$mag)^1.3
pal <- colorFactor(c("navy", "red"), domain = c("> 6", "< 6"))
QK <- ifelse(Earthquakes$mag >= 6, "> 6", "< 6")
leaflet(data = Earthquakes) %>% addTiles() %>% addPolylines(data = plaques)%>% setView(-71.0382679, -36, zoom = 4) %>%
addCircleMarkers(~longitude, ~latitude, popup = ~as.character(time), label = ~as.character(mag), fillOpacity = 0.5, radius = MAG, color = ~pal(QK))
#%>% addLegend(position= "topright", pal = pal, values= ~QK, title = "Magnitud")
```
En la siguiente serie de tiempo, se muestran los temblores del ultimo mes, la linea punteada roja muestra el último sismo sobre `r ifelse(max(Chile$mag) < 6,max(Chile$mag), 6)` que ha ocurrido.
```{r, message=FALSE, echo=FALSE, warning=FALSE}
dyUnzoom <-function(dygraph) {
dyPlugin(
dygraph = dygraph,
name = "Unzoom",
path = system.file("plugins/unzoom.js", package = "dygraphs")
)
}
Earthquakes <- dplyr::filter(Earthquakes, latitude < -17 & latitude > -60 & longitude < -65 & longitude > -75)
Earthquakes <- as.data.frame(Earthquakes)
TimeSeries <- xts(Earthquakes[,c("mag")],Earthquakes[,"time"])
dygraph(TimeSeries, main = "Sismos ultimos 30 dias en Chile", ylab = "Magnitud") %>% dyRangeSelector() %>% dyOptions(drawPoints = TRUE, pointSize = 2) %>% dyHighlight(highlightCircleSize = 5) %>% dyLegend("follow") %>% dyUnzoom() %>% dyEvent(Last, "Ultimo evento", labelLoc = "bottom", color ="red")
```
<!--chapter:end:Earthquake.Rmd-->
---
title: "Does the recent Bulls winning streak mean something?"
author: "Derek Corcoran and Nick Watanabe"
date: "December 20, 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, cache = TRUE, warning = FALSE, message = FALSE)
```
```{r}
library(dplyr)
library(lubridate)
library(SpatialBall2)
library(gridExtra)
library(ggplot2)
Season2018 <- readRDS("Season2018.rds")
NM <- filter(Season2018, GAME_DATE >= dmy("8/12/2017"))
WONM <- filter(Season2018, GAME_DATE < dmy("8/12/2017"))
```
### Shot charts with and without Nikola Mirotic
Since Nikola Mirotic has just played 6 games, there are too few shots to make a passable shot chart for the Chicago Bulls with him, so we will have to rely on team stats to figure what is going on.
```{r, fig.width=6, fig.height=12}
Without <- OffShotSeasonGraphTeam(Seasondata = WONM, team = "Chi") + ggtitle("Offensive without Mirotic")
With <- OffShotSeasonGraphTeam(Seasondata = NM, team = "Chi", quant = 0.05)+ ggtitle("Offensive with Mirotic")
grid.arrange(Without, With, ncol = 1)
```
### Stats without Nikola Mirotic
As seen in the table below, before Nikola Mirotic came back, the Bulls ranked 27th in the league in Adjusted points per shot (APPS), and then moved to a more respectable 14th after his return. The defense has not changed all that much, but they improved a tick going from being 15th to 13th in adjusted points allowed per shot.
```{r}
statsWONM <- SpatialBall2::TeamStats(WONM)
```
```{r}
statsWONM[[1]]$Rank <- 1:30
statsWONM[[2]]$Rank <- 1:30
knitr::kable(dplyr::filter(statsWONM[[1]], TEAM_NAME == "Chi"))
knitr::kable(dplyr::filter(statsWONM[[2]], DefTeam == "Chi"))
```
### Stats with Nikola Mirotic
```{r}
statsNM <- SpatialBall2::TeamStats(NM)
```
```{r}
statsNM[[1]]$Rank <- 1:30
statsNM[[2]]$Rank <- 1:30
knitr::kable(dplyr::filter(statsNM[[1]], TEAM_NAME == "Chi"))
knitr::kable(dplyr::filter(statsNM[[2]], DefTeam == "Chi"))
```
Chicago has diminished the percentage of 3-point shots taken since Mirotic came back, moving from 36% of their shots being taken from beyond the arc to only 26%. Overall, the main change for them has been the shooting efficiency, as their 2-point shooting percentage rose from 45.7% to 51.5% and their 3-point pct from 34.2% to 38.2%.
```{r}
SpatialBall2::PointShotSeasonGraphPlayer(Seasondata = Season2018, player = "Nikola Mirotic", kernel = FALSE) + ggtitle("Shots taken by Mirotic")
```
In this season, Mirotic is shooting an effective field goal percentage of 63%, while having a career 51.1% eFG%. This includes him making over 50% of his 3’s, when he is a career 35.5% 3-point shooter. All this while having a 28% usage rate, the highest in his career by far, and shooting all over the court as we see above. If Mirotic can maintain this level of production and efficiency, the Bulls could certainly have a better season than predicted. However, all this points to an unsustainable efficiency, and a possible regression to the mean for the Nikola and the Bulls.
```{r}
knitr::include_graphics("https://upload.wikimedia.org/wikipedia/commons/3/34/Nikola_Mirotic_%2816240996134%29.jpg")
```
<!--chapter:end:Mirotic.Rmd-->
---
title: "El problema de los alergenos en Chile"
author: "Derek Corcoran"
output: html_document
bibliography: bibliography.bib
csl: nature.csl
---
### Resumen
Santiago de Chile, es una de las ciudades del país con mayor contaminación de aire. Pese a esto los planificadores urbanos de la zona, no han planificado el plantar vegetación urbana acorde a esta situación. Sinó que al contrario, han elegido plantar árboles exóticos con producción excesiva de polen, llegando a veces a valores de hasta 3000 particulas de polen por metro cúbico, siendo que 70, es considerado un nivel muy alto. Se comparan los niveles de alergenos para Santiago con los de Valparaiso y Talca, y se demuestra que Santiago es la ciudad que se ha planificado peor en cuanto a los árboles que se han plantado en la región, y que esto podría estar afectando tanto el bienestar de los ciudadanos de Santiago, como su economía debido a gastos en antihistamínicos.
### Introducción
Dentro de los parámetros deseados del diseño de espacios verdes urbanos tomando en cuenta las alergias, se encuentran, el plantar gran diversidad de especies para evitar picos altos de polinización de una especie única, el no plantar especies exóticas para evitar exponer a la población urbana a nuevos agentes alergenos, y en el caso de tratarse de especies dioicas, no plantar individuos masculinos para evitar el polen [@carinanos2011urban]. En la población mundial entre el 10 y el 30 porciento de la población es alergica[@berger2003overview].
Si bien en santiago se ha determinado que los árboles hen beneficiado la calidad del aire [@escobedo2008analyzing], la elección de las especies plantadas pueden tener un costo económico y social altisimo para la ciudadania, en Estados Unidos, se han estimado costos económicos directos e indirectos de 4912 dolares anuales por persona [@o2004burden]. Los costos directos concideran medicamentos, hospitalizaciones entre otras. En tanto que los costos indirectos incluyen menor aprendisaje y rendimiento, e incluso en un 25% de los alergicos, perdida de días de trabajo o escuela [@tanner1999effect], además de bajas de autoestima y/o disminución de la vida social y deportiva, llevando al sedentarismo [@fineman2002burden].
Según el Instituto de Salud Publica de Chile, tan solo entre julio 2015 y julio 2016 se vendieron 6.265.562 de antialérgicos en el país.
### Resultados
#### Santiago
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
```
En el siguiente gráfico, vemos que en los últimos 15 años (2002 al 2017), santiago ha tenido ciclos en los cuales los niveles más altos de polen se encuentran principalemnte en los meses de Septiembre y Ocutbre y destaca dentro de los volumenes de polen el Platano oriental (*Platanus orientalis*) que puede generar hasta 3000 particulas de polen por metro cúbico, siendo este considerado en niveles altos de alergia cuando llega a 70.
```{r}
if (!require("pacman")) install.packages("pacman")
pacman::p_load(rvest, lubridate, stringr, dplyr, ggplot2, tidyr, dygraphs, xts)
Alergia <- readRDS("Alergia.rds")
TimeSeries1 <- xts(Alergia[,c("platano_oriental")],Alergia[,"Fechas"])
TimeSeries2 <- xts(Alergia[,c("arboles_total")],Alergia[,"Fechas"])
TimeSeries3 <- xts(Alergia[,c("pastos")],Alergia[,"Fechas"])
TimeSeries <- cbind(TimeSeries1, TimeSeries2)
TimeSeries <- cbind(TimeSeries, TimeSeries3)
colnames(TimeSeries) <- c("Platano Oriental", "Arboles total", "Pastos")
dyUnzoom <-function(dygraph) {
dyPlugin(
dygraph = dygraph,
name = "Unzoom",
path = system.file("plugins/unzoom.js", package = "dygraphs")
)
}
dygraph(TimeSeries , ylab = "Particulas de polen/m³ de aire") %>% dyRangeSelector() %>% dyOptions(drawPoints = TRUE, pointSize = 2) %>% dyHighlight(highlightCircleSize = 5) %>% dyLegend("always") %>% dyUnzoom() %>% dyOptions(stackedGraph = TRUE)
```
```{r}
Weekly <- Alergia %>% select(Semana, platano_oriental) %>%group_by(Semana) %>% summarise_all(funs(mean, sd, max, min))
p <- ggplot(Weekly, aes(x = Semana, y = mean))+ geom_ribbon(aes(ymax = max, ymin = min, fill = "red")) + geom_ribbon(aes(ymax = mean + sd, ymin = mean - sd, fill = "blue"), alpha = 1) + geom_line() + scale_fill_manual(name = "leyenda", values = c("blue", "red"), labels = c('Error estándar','Extremos')) + ylab("polen de platano oriental /m³ de aire") + theme_classic() + theme(legend.position="bottom") + scale_x_continuous(breaks=seq(from = 2.5, to = 49.5, by = 4), labels = c("Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"))
```
Para el siguiente gráfico, debido a que distintas plantas generan distintos niveles de alergia, estandarizamos los niveles de polen, debido ha esto, cada vez que en el gráfico se sobrepase la linea punteada roja, estamos ante niveles altos de alergia, si el valor llega a dos, significa que tenemos a el doble un nivel ya cosiderado alto. Los valores que se muestran para santiago son en las lineas los promedios desde el 2002, y en el colores la desviación estadard de la media.
```{r}
Weekly2 <- Alergia %>% select(Semana, platano_oriental, arboles_total, pastos) %>% mutate(platano_oriental = platano_oriental/70, arboles_total = arboles_total/100, pastos = pastos/25) %>% gather(key = Especie, value = Polen, -Semana) %>%group_by(Semana, Especie) %>% summarise_if(is.numeric, funs(mean, sd, max, min))
Weekly2 <- as.data.frame(Weekly2)
ggplot(Weekly2, aes(x = Semana, y = mean))+ geom_ribbon(aes(ymax = mean + sd, ymin = mean - sd, fill = Especie), alpha = 0.5) + geom_line(aes(lty = Especie)) + ylab("Nivel estandarizado de polen") + xlab("Mes") + theme_classic() + theme(legend.position="bottom") + scale_x_continuous(breaks=seq(from = 2.5, to = 49.5, by = 4), labels = c("Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic")) + geom_hline(yintercept = 1, lty=2, color = "red") + annotate("text", x = 8, y = 2, label = "Niveles altos de polen", color = "red")
```
Se observa como si bién en noviembre y diciembre, los pastos llegan a niveles altos de alregenos, mayormente no sobrepasan por mucho ese nivel, mientras que el platano oriental llega, en septiembreme, en promedio a estar 13.6 veces sobre niveles considerados altos.
#### Comparación con otras ciudades de Chile
```{r}
Valpo <- readRDS("Valpo.rds")
Alergia <- readRDS("Alergia.rds")
Talca <- readRDS("Talca.rds")
AlergiaTotal <- Alergia %>% mutate(Santiago = (arboles_total/100) + (platano_oriental/70) + (pastos/25)) %>% select(Fechas,Anno, Mes, Semana, Santiago)
ValpoTotal <- Valpo %>% mutate(Valparaiso = (arboles_total/100) + (platano_oriental/70) + (pastos/25)) %>% select(Anno, Mes, Semana, Valparaiso)
TalcaTotal <- Talca %>% mutate(Talca = (arboles_total/100) + (platano_oriental/70) + (pastos/25)) %>% select(Anno, Mes, Semana, Talca)
PolenTotal <- full_join(AlergiaTotal, ValpoTotal)
PolenTotal <- full_join(PolenTotal, TalcaTotal)
PolenTotal <- PolenTotal[complete.cases(PolenTotal),]
SUMMAR <- PolenTotal %>% select(Mes, Santiago, Valparaiso, Talca) %>%group_by(Mes) %>% dplyr::summarise_all(funs(mean))
Stgo <- xts(PolenTotal[,c("Santiago")],PolenTotal[,"Fechas"])
ValpoT <- xts(PolenTotal[,c("Valparaiso")],PolenTotal[,"Fechas"])
TalcaT <- xts(PolenTotal[,c("Talca")],PolenTotal[,"Fechas"])
PolenTotal <- cbind(Stgo, ValpoT)
PolenTotal <- cbind(PolenTotal, TalcaT)
colnames(PolenTotal)<- c("Santiago", "Valparaiso", "Talca")
dyUnzoom <-function(dygraph) {
dyPlugin(
dygraph = dygraph,
name = "Unzoom",
path = system.file("plugins/unzoom.js", package = "dygraphs")
)
}
dygraph(PolenTotal , ylab = "polen total /m³ de aire") %>% dyRangeSelector() %>% dyOptions(drawPoints = TRUE, pointSize = 2) %>% dyHighlight(highlightCircleSize = 5) %>% dyLegend("always") %>% dyUnzoom() %>% dyOptions(stackedGraph = TRUE)%>% dyLimit(1, color = "red")
```
```{r}
knitr::kable(SUMMAR)
```
## Bibliografía
<!--chapter:end:Polen.Rmd-->
---
title: "NBA Projections 2018 season"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)
```
These are the projected standings predicted by our spatial-based algorithm as of `r format(Sys.time(), '%d %B, %Y')`
```{r Shotscrub, echo=FALSE, message=FALSE, warning=FALSE}
if (!require("pacman")) install.packages("pacman")
pacman::p_load(rjson, grid, gridExtra, png, RCurl, ggplot2, jpeg, hexbin, sp, knitr, dplyr, lubridate, purrr)
by_team <- readRDS("by_team.rds")
Season2018 <- readRDS("Season2018.rds")
startScrape <- format((max(Season2018$GAME_DATE)), '%m/%d/%Y')
teamID <- by_team$team_id
teamName <- by_team$team_city
Season2018b <- list()
shotURLtotal <- paste("http://stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2017-18&ContextFilter=&ContextMeasure=FGA&DateFrom=", startScrape ,"&DateTo=&GameID=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerID=0&PlusMinus=N&Position=&Rank=N&RookieYear=&Season=2017-18&SeasonSegment=&SeasonType=Regular+Season&TeamID=0&VsConference=&VsDivision=&mode=Advanced&showDetails=0&showShots=1&showZones=0&PlayerPosition=", sep = "")
# import from JSON
Season2018b <- fromJSON(file = shotURLtotal, method="C")
Names <- Season2018b$resultSets[[1]][[2]]
# unlist shot data, save into a data frame
Season2018b <- data.frame(matrix(unlist(Season2018b$resultSets[[1]][[3]]), ncol = 24, byrow = TRUE))
colnames(Season2018b) <- Names
# covert x and y coordinates into numeric
Season2018b$LOC_X <- as.numeric(as.character(Season2018b$LOC_X))
Season2018b$LOC_Y <- as.numeric(as.character(Season2018b$LOC_Y))
Season2018b$TEAM_NAME <- gsub("Detroit Pistons", "Det", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Atlanta Hawks", "Atl", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Chicago Bulls", "Chi", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Boston Celtics", "Bos", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Cleveland Cavaliers", "Cle", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("New Orleans Pelicans", "NO", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Golden State Warriors", "GSW", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Orlando Magic", "ORL", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Washington Wizards", "Was", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Philadelphia 76ers", "Phi", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Brooklyn Nets", "Bkn", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Utah Jazz", "Uta", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Miami Heat", "Mia", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Charlotte Hornets", "Cha", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Toronto Raptors", "Tor", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Indiana Pacers", "Ind", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Houston Rockets", "Hou", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Denver Nuggets", "Den", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Memphis Grizzlies", "Mem", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("New York Knicks", "NY", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Milwaukee Bucks", "Mil", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Oklahoma City Thunder", "Okc", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("San Antonio Spurs", "Sas", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Dallas Mavericks", "Dal", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Phoenix Suns", "Pho", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Portland Trail Blazers", "Por", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("LA Clippers", "Lac", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Sacramento Kings", "Sac", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Los Angeles Lakers", "Lal", Season2018b$TEAM_NAME)
Season2018b$TEAM_NAME <- gsub("Minnesota Timberwolves", "Min", Season2018b$TEAM_NAME)
####HOME VISITOR
Season2018b$HTM <- gsub("DET", "Det", Season2018b$HTM)
Season2018b$HTM <- gsub("ATL", "Atl", Season2018b$HTM)
Season2018b$HTM <- gsub("CHI", "Chi", Season2018b$HTM)
Season2018b$HTM <- gsub("BOS", "Bos", Season2018b$HTM)
Season2018b$HTM <- gsub("CLE", "Cle", Season2018b$HTM)
Season2018b$HTM <- gsub("NOP", "NO", Season2018b$HTM)
Season2018b$HTM <- gsub("GSW", "GSW", Season2018b$HTM)
Season2018b$HTM <- gsub("ORL", "ORL", Season2018b$HTM)
Season2018b$HTM <- gsub("WAS", "Was", Season2018b$HTM)
Season2018b$HTM <- gsub("PHI", "Phi", Season2018b$HTM)
Season2018b$HTM <- gsub("BKN", "Bkn", Season2018b$HTM)
Season2018b$HTM <- gsub("UTA", "Uta", Season2018b$HTM)
Season2018b$HTM <- gsub("MIA", "Mia", Season2018b$HTM)
Season2018b$HTM <- gsub("CHA", "Cha", Season2018b$HTM)
Season2018b$HTM <- gsub("TOR", "Tor", Season2018b$HTM)
Season2018b$HTM <- gsub("IND", "Ind", Season2018b$HTM)
Season2018b$HTM <- gsub("HOU", "Hou", Season2018b$HTM)
Season2018b$HTM <- gsub("DEN", "Den", Season2018b$HTM)
Season2018b$HTM <- gsub("MEM", "Mem", Season2018b$HTM)
Season2018b$HTM <- gsub("NYK", "NY", Season2018b$HTM)
Season2018b$HTM <- gsub("MIL", "Mil", Season2018b$HTM)
Season2018b$HTM <- gsub("OKC", "Okc", Season2018b$HTM)
Season2018b$HTM <- gsub("SAS", "Sas", Season2018b$HTM)
Season2018b$HTM <- gsub("DAL", "Dal", Season2018b$HTM)
Season2018b$HTM <- gsub("PHX", "Pho", Season2018b$HTM)
Season2018b$HTM <- gsub("POR", "Por", Season2018b$HTM)
Season2018b$HTM <- gsub("LAC", "Lac", Season2018b$HTM)
Season2018b$HTM <- gsub("SAC", "Sac", Season2018b$HTM)
Season2018b$HTM <- gsub("LAL", "Lal", Season2018b$HTM)
Season2018b$HTM <- gsub("MIN", "Min", Season2018b$HTM)
###Visitor
Season2018b$VTM <- gsub("DET", "Det", Season2018b$VTM)
Season2018b$VTM <- gsub("ATL", "Atl", Season2018b$VTM)
Season2018b$VTM <- gsub("CHI", "Chi", Season2018b$VTM)
Season2018b$VTM <- gsub("BOS", "Bos", Season2018b$VTM)
Season2018b$VTM <- gsub("CLE", "Cle", Season2018b$VTM)
Season2018b$VTM <- gsub("NOP", "NO", Season2018b$VTM)
Season2018b$VTM <- gsub("GSW", "GSW", Season2018b$VTM)
Season2018b$VTM <- gsub("ORL", "ORL", Season2018b$VTM)
Season2018b$VTM <- gsub("WAS", "Was", Season2018b$VTM)
Season2018b$VTM <- gsub("PHI", "Phi", Season2018b$VTM)
Season2018b$VTM <- gsub("BKN", "Bkn", Season2018b$VTM)
Season2018b$VTM <- gsub("UTA", "Uta", Season2018b$VTM)
Season2018b$VTM <- gsub("MIA", "Mia", Season2018b$VTM)
Season2018b$VTM <- gsub("CHA", "Cha", Season2018b$VTM)
Season2018b$VTM <- gsub("TOR", "Tor", Season2018b$VTM)
Season2018b$VTM <- gsub("IND", "Ind", Season2018b$VTM)
Season2018b$VTM <- gsub("HOU", "Hou", Season2018b$VTM)
Season2018b$VTM <- gsub("DEN", "Den", Season2018b$VTM)
Season2018b$VTM <- gsub("MEM", "Mem", Season2018b$VTM)
Season2018b$VTM <- gsub("NYK", "NY", Season2018b$VTM)
Season2018b$VTM <- gsub("MIL", "Mil", Season2018b$VTM)
Season2018b$VTM <- gsub("OKC", "Okc", Season2018b$VTM)
Season2018b$VTM <- gsub("SAS", "Sas", Season2018b$VTM)
Season2018b$VTM <- gsub("DAL", "Dal", Season2018b$VTM)
Season2018b$VTM <- gsub("PHX", "Pho", Season2018b$VTM)
Season2018b$VTM <- gsub("POR", "Por", Season2018b$VTM)
Season2018b$VTM <- gsub("LAC", "Lac", Season2018b$VTM)
Season2018b$VTM <- gsub("SAC", "Sac", Season2018b$VTM)
Season2018b$VTM <- gsub("LAL", "Lal", Season2018b$VTM)
Season2018b$VTM <- gsub("MIN", "Min", Season2018b$VTM)
Season2018b$GAME_DATE <- ymd(Season2018b$GAME_DATE)
Season2018 <- full_join(Season2018, Season2018b)
```
```{r schedulescrub, echo=FALSE, message=FALSE, warning=FALSE, cache=TRUE}
pacman::p_load(XML, lubridate, rvest, dplyr)
#Gather data
Months <- c("october", "november", "december", "january", "february", "march", "april")
Years <- c(2018)
URLs <- list()
for(i in 1:length(Years)){
URLs[[i]] <- paste("http://www.basketball-reference.com/leagues/NBA_", Years[i],"_games-", Months,".html", sep = "")
}
URLs <- do.call("c", URLs)
URLs <- data.frame(URLs = URLs, Year = as.numeric(gsub("\\D", "", URLs)))
URLs$URLs <- as.character(URLs$URLs)
schedule <- list()
# import from JSON
for(i in 1:nrow(URLs)){
schedule[[i]] <- read_html(URLs$URLs[i])%>% html_table(fill=TRUE)%>% .[[1]]
}
schedule <- do.call("rbind", schedule)
schedule$Date <- mdy(as.character(schedule$Date))
schedule[,4] <- as.numeric(as.character(schedule[,4]))
schedule[,6] <- as.numeric(as.character(schedule[,6]))
schedule$Season <- 2018
schedule[,3] <- gsub("Detroit Pistons", "Det", schedule[,3])
schedule[,3] <- gsub("Atlanta Hawks", "Atl", schedule[,3])
schedule[,3] <- gsub("Chicago Bulls", "Chi", schedule[,3])
schedule[,3] <- gsub("Boston Celtics", "Bos", schedule[,3])
schedule[,3] <- gsub("Cleveland Cavaliers", "Cle", schedule[,3])
schedule[,3] <- gsub("New Orleans Pelicans", "NO", schedule[,3])
schedule[,3] <- gsub("Golden State Warriors", "GSW", schedule[,3])
schedule[,3] <- gsub("Orlando Magic", "ORL", schedule[,3])
schedule[,3] <- gsub("Washington Wizards", "Was", schedule[,3])
schedule[,3] <- gsub("Philadelphia 76ers", "Phi", schedule[,3])
schedule[,3] <- gsub("Brooklyn Nets", "Bkn", schedule[,3])
schedule[,3] <- gsub("Utah Jazz", "Uta", schedule[,3])
schedule[,3] <- gsub("Miami Heat", "Mia", schedule[,3])
schedule[,3] <- gsub("Charlotte Hornets", "Cha", schedule[,3])
schedule[,3] <- gsub("Toronto Raptors", "Tor", schedule[,3])
schedule[,3] <- gsub("Indiana Pacers", "Ind", schedule[,3])
schedule[,3] <- gsub("Houston Rockets", "Hou", schedule[,3])
schedule[,3] <- gsub("Denver Nuggets", "Den", schedule[,3])
schedule[,3] <- gsub("Memphis Grizzlies", "Mem", schedule[,3])
schedule[,3] <- gsub("New York Knicks", "NY", schedule[,3])
schedule[,3] <- gsub("Milwaukee Bucks", "Mil", schedule[,3])
schedule[,3] <- gsub("Oklahoma City Thunder", "Okc", schedule[,3])
schedule[,3] <- gsub("San Antonio Spurs", "Sas", schedule[,3])
schedule[,3] <- gsub("Dallas Mavericks", "Dal", schedule[,3])
schedule[,3] <- gsub("Phoenix Suns", "Pho", schedule[,3])
schedule[,3] <- gsub("Portland Trail Blazers", "Por", schedule[,3])
schedule[,3] <- gsub("Los Angeles Clippers", "Lac", schedule[,3])
schedule[,3] <- gsub("Sacramento Kings", "Sac", schedule[,3])
schedule[,3] <- gsub("Los Angeles Lakers", "Lal", schedule[,3])
schedule[,3] <- gsub("Minnesota Timberwolves", "Min", schedule[,3])
schedule[,3] <- gsub("Charlotte Bobcats", "Cha", schedule[,3])
schedule[,3]<- gsub("New Orleans Hornets", "NO", schedule[,3])
schedule[,5] <- gsub("Detroit Pistons", "Det", schedule[,5])
schedule[,5] <- gsub("Atlanta Hawks", "Atl", schedule[,5])
schedule[,5] <- gsub("Chicago Bulls", "Chi", schedule[,5])
schedule[,5] <- gsub("Boston Celtics", "Bos", schedule[,5])
schedule[,5] <- gsub("Cleveland Cavaliers", "Cle", schedule[,5])
schedule[,5] <- gsub("New Orleans Pelicans", "NO", schedule[,5])
schedule[,5] <- gsub("Golden State Warriors", "GSW", schedule[,5])
schedule[,5] <- gsub("Orlando Magic", "ORL", schedule[,5])
schedule[,5] <- gsub("Washington Wizards", "Was", schedule[,5])
schedule[,5] <- gsub("Philadelphia 76ers", "Phi", schedule[,5])
schedule[,5] <- gsub("Brooklyn Nets", "Bkn", schedule[,5])
schedule[,5] <- gsub("Utah Jazz", "Uta", schedule[,5])
schedule[,5] <- gsub("Miami Heat", "Mia", schedule[,5])
schedule[,5] <- gsub("Charlotte Hornets", "Cha", schedule[,5])
schedule[,5] <- gsub("Toronto Raptors", "Tor", schedule[,5])
schedule[,5] <- gsub("Indiana Pacers", "Ind", schedule[,5])
schedule[,5] <- gsub("Houston Rockets", "Hou", schedule[,5])
schedule[,5] <- gsub("Denver Nuggets", "Den", schedule[,5])
schedule[,5] <- gsub("Memphis Grizzlies", "Mem", schedule[,5])
schedule[,5] <- gsub("New York Knicks", "NY", schedule[,5])
schedule[,5] <- gsub("Milwaukee Bucks", "Mil", schedule[,5])
schedule[,5] <- gsub("Oklahoma City Thunder", "Okc", schedule[,5])
schedule[,5] <- gsub("San Antonio Spurs", "Sas", schedule[,5])
schedule[,5] <- gsub("Dallas Mavericks", "Dal", schedule[,5])
schedule[,5] <- gsub("Phoenix Suns", "Pho", schedule[,5])
schedule[,5] <- gsub("Portland Trail Blazers", "Por", schedule[,5])
schedule[,5] <- gsub("Los Angeles Clippers", "Lac", schedule[,5])
schedule[,5] <- gsub("Sacramento Kings", "Sac", schedule[,5])
schedule[,5] <- gsub("Los Angeles Lakers", "Lal", schedule[,5])
schedule[,5] <- gsub("Minnesota Timberwolves", "Min", schedule[,5])
schedule[,5] <- gsub("Charlotte Bobcats", "Cha", schedule[,5])
schedule[,5]<- gsub("New Orleans Hornets", "NO", schedule[,5])
```
```{r simulatingGames, echo=FALSE, message=FALSE, warning=FALSE}
pacman::p_load(SpatialBall2, dplyr,XML, lubridate, rvest)
colnames(schedule) <- c("Date", "Start..ET.","VTM", "PTS_Visitor", "HTM", "PTS_Home", "X", "X2", "X3","Notes", "Season")
schedule <- dplyr::select(schedule, Date, VTM, PTS_Visitor, HTM, PTS_Home, Season)
future_games <- schedule[schedule$Date >= Sys.Date(),]
results <- list()
for(i in 1:nrow(future_games)){
results[[i]] <- Get_Apps(HomeTeam = future_games$HTM[i], VisitorTeam = future_games$VTM[i], Seasondata = Season2018)
message(paste("simulating", i ,"of", nrow(future_games)))
}
results <- do.call(rbind, results)
future_games <- cbind(future_games, results)
future_games$Home <- ifelse(future_games$spread < 0, "W", "L")
future_games$Visit <- ifelse(future_games$spread > 0, "W", "L")
Home <- cbind(future_games$HTM, future_games$Home)
colnames(Home) <- c("Team", "Result")
Visit <- cbind(future_games$VTM, future_games$Visit)
colnames(Visit) <- c("Team", "Result")
AddedStand <- data.frame(rbind(Home, Visit))
#Wins
AddedStand_W <- dplyr::filter(AddedStand, Result == "W")
AddedStand_W <- group_by(AddedStand_W, Team)
AddedStand_W <- dplyr::summarize(AddedStand_W, W = n())
#Loses
AddedStand_L <- dplyr::filter(AddedStand, Result == "L")
AddedStand_L <- group_by(AddedStand_L, Team)
AddedStand_L <- dplyr::summarize(AddedStand_L, L = n())
AddedStand <- merge.data.frame(AddedStand_W, AddedStand_L, all = TRUE)
#####Standing scraper
Standings <- "http://www.basketball-reference.com/leagues/NBA_2018.html"
Standings <- read_html(Standings)%>% html_table(fill=TRUE)%>% .[1:2]
Standings <- list(Western = Standings[[2]], Eastern = Standings[[1]])
Standings[[1]]$Conference <- c("West")
Standings[[2]]$Conference <- c("East")
colnames(Standings[[1]]) <- c("Team", "Current-W", "Current-L", "pct", "GB", "PS/G", "PA/G", "SRS", "Conference")
colnames(Standings[[2]]) <- c("Team", "Current-W", "Current-L", "pct", "GB", "PS/G", "PA/G", "SRS", "Conference")
Standings <- rbind(Standings[[1]], Standings[[2]])
Standings <- Standings[,c(1,2,3,9)]
Standings$Team <- gsub("76ers", "Phi", Standings$Team)
Standings$Team <- gsub("(?<=\\b[A-Z])[^A-Z]+", "", Standings$Team, perl = TRUE)
Standings$Team <- gsub("DP", "Det", Standings$Team)
Standings$Team<- gsub("AH", "Atl", Standings$Team)
Standings$Team <- gsub("CB", "Chi", Standings$Team)
Standings$Team<- gsub("BC", "Bos", Standings$Team)
Standings$Team<- gsub("CC", "Cle", Standings$Team)
Standings$Team<- gsub("NOP", "NO", Standings$Team)
Standings$Team<- gsub("OM", "ORL", Standings$Team)
Standings$Team<- gsub("WW", "Was", Standings$Team)
Standings$Team<- gsub("BN", "Bkn", Standings$Team)
Standings$Team<- gsub("UJ", "Uta", Standings$Team)
Standings$Team<- gsub("MH", "Mia", Standings$Team)
Standings$Team<- gsub("CH", "Cha", Standings$Team)
Standings$Team<- gsub("TR", "Tor", Standings$Team)
Standings$Team<- gsub("IP", "Ind", Standings$Team)
Standings$Team<- gsub("HR", "Hou", Standings$Team)
Standings$Team<- gsub("DN", "Den", Standings$Team)
Standings$Team<- gsub("MG", "Mem", Standings$Team)
Standings$Team<- gsub("NYK", "NY", Standings$Team)
Standings$Team<- gsub("MB", "Mil", Standings$Team)
Standings$Team<- gsub("OCT", "Okc", Standings$Team)
Standings$Team<- gsub("SAS", "Sas", Standings$Team)
Standings$Team<- gsub("DM", "Dal", Standings$Team)
Standings$Team<- gsub("PS", "Pho", Standings$Team)
Standings$Team<- gsub("PTB", "Por", Standings$Team)
Standings$Team<- gsub("LAC", "Lac", Standings$Team)
Standings$Team<- gsub("SK", "Sac", Standings$Team)
Standings$Team<- gsub("LAL", "Lal", Standings$Team)