-
Notifications
You must be signed in to change notification settings - Fork 0
/
writers.R
1277 lines (1077 loc) · 53.5 KB
/
writers.R
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
#### Writers ------------------------
# At the beginning of a new season, use this script to update all necessary data
#
# Alberto Sanchez Rodelgo
#### --------------------------------
########## PLAYERS ###########
## Update the historical players database: playersHist
write_playersHist <- function(fromYear, toYear) {
# Look in basketballreference.com and loop for all seasons
# Example: http://www.basketball-reference.com/leagues/NBA_2017_per_game.html
require(httr)
require(tidyverse)
library(rvest)
thisYear <- substr(Sys.Date(),1,4)
##### ALL SEASONS ########
#fromYear <- 1980
##### NEW SEASON ########
#fromYear <- as.numeric(thisYear)-seasonOffset
# read new stats only from fromYear to toYear
playersHist <- data.frame()
for (year in fromYear:toYear){
url <- paste0("http://www.basketball-reference.com/leagues/NBA_",year,"_per_game.html")
thisSeasonStats <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="per_game_stats"]') %>%
html_table(fill = TRUE)
thisSeasonStats <- thisSeasonStats[[1]] %>% filter(!(Player == "Player")) %>%
mutate(Season = paste0(year-1,"-",year)) %>%
select(-Rk)
if (nrow(playersHist)>0) playersHist <- bind_rows(playersHist,thisSeasonStats)
else playersHist <- thisSeasonStats
}
playersHist <- mutate_at(playersHist, vars(c(3,5:(ncol(playersHist)-1))), funs(as.numeric))
playersHist[is.na(playersHist)] <- 0
names(playersHist) <- gsub("%",".",names(playersHist),fixed=TRUE)
names(playersHist) <- gsub("2","X2",names(playersHist))
names(playersHist) <- gsub("3","X3",names(playersHist))
names(playersHist) <- gsub("PS/G","PTS",names(playersHist),fixed=TRUE)
if (firstYear==thisYear) {
playersHistOLD <- read.csv("data/playersHist.csv", stringsAsFactors = FALSE)
playersHist <- bind_rows(playersHistOLD,playersHist)
}
playersHist<- filter(playersHist, Season > "1978-1979") %>%
distinct(Player, Tm, Season, .keep_all = TRUE)
write.csv(playersHist, "data/playersHist.csv",row.names = FALSE)
}
# Pre-compute tsne_points for all ages to save time as these computations don't really
# depend on the player selected.
write_tsneBlocks <- function(){
tsneBlock <- list()
num_iter <- 300
max_num_neighbors <- 20
for (a in 18:41){ # ages 18 to 41
tsneBlock[[a]] <- .tSNE_compute(num_iter, max_num_neighbors, a)
write.csv(tsneBlock[[a]],paste0("data/tsneBlock","_",a,".csv"),row.names = FALSE)
}
}
# write current or previous season rosters
write_currentRosters_rostersLastSeason <- function(previousSeason = FALSE){
thisSeason = substr(Sys.Date(),1,4)
library(httr)
new_rosters <- data.frame()
thisSeason <- as.numeric(thisSeason) + 1
current_rosters <- data.frame()
playersNew <- playersHist %>% # keep only players last season
filter(Season == max(as.character(Season))) %>%
mutate(Season = as.factor(paste0(as.numeric(substr(Season,1,4))+1,"-",as.numeric(substr(Season,1,4))+2)))
playersNew <- filter(playersNew,!(Tm == "TOT"))
for (thisTeam in unique(playersNew$Tm)){
url <- paste0("https://www.basketball-reference.com/teams/",thisTeam,"/",thisSeason,".html")
if (status_code(GET(url)) == 200){ # successful response
getRoster <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="roster"]') %>%
html_table(fill = TRUE)
thisRoster <- getRoster[[1]] %>% select(-`No.`)
names(thisRoster)[which(names(thisRoster)=='')] <- "Nationality"
thisRoster <- mutate(thisRoster, Tm = thisTeam, Exp = as.character(Exp))
if (nrow(current_rosters)>0){
current_rosters <- bind_rows(current_rosters,thisRoster)
} else{
current_rosters <- thisRoster
}
}
}
names(current_rosters) <- gsub(" ","_",names(current_rosters))
#names(current_rosters) <- c(names(current_rosters)[1:5],"Birth_Date","Nationality","Experience","College","Team")
# I need to compute their current ages for the prediction model is based on their age
current_rosters <- mutate(current_rosters, Age = thisSeason - as.numeric(substr(Birth_Date,nchar(Birth_Date)-3,nchar(Birth_Date))),
Season = paste0(thisSeason-1,"-",thisSeason))
# write current_rosters or rostersLastSeason depending on value of thisSeason
if (previousSeason) {
write.csv(current_rosters, "data/rostersLastSeason.csv",row.names = FALSE)
} else {
write.csv(current_rosters, "data/currentRosters.csv",row.names = FALSE)
}
}
# write players predicted stats for an upcoming season
# imports: playersHist.csv
# calls several helpers
write_playersNewPredicted <- function() {
# update currentRosters, europePlayers and College players from write_rookiesDraft.R
#current_rosters <- read.csv("data/currentRosters.csv", stringsAsFactors = FALSE)
#rookies <- read.csv("data/rookies.csv",stringsAsFactors = FALSE)
#collegePlayers <- read.csv("data/collegePlayers.csv", stringsAsFactors = FALSE)
#rookieStats <- read.csv("data/rookieStats.csv", stringsAsFactors = FALSE)
#europePlayers <- read.csv("data/europePlayers.csv", stringsAsFactors = FALSE)
playersNew <- playersHist %>%
filter(Season == max(as.character(Season))) %>%
mutate(Season = as.factor(paste0(as.numeric(substr(Season,1,4))+1,"-",as.numeric(substr(Season,1,4))+2)))
playersNewPredicted <- data.frame()
for (team in unique(playersNew$Tm)){
thisTeam <- filter(playersNew, Tm == team)
thisTeamStats <- data.frame()
counter <- 0 # keep count
for (player in thisTeam$Player){
counter <- counter + 1
#if (!(player %in% playersNewPredicted$Player)){ # skip running all. Start over where it failed
thisPlayer <- filter(thisTeam, Player == player)
#thisPlayer <- filter(playersNew, Player == player)
print(paste0("Team: ", team,": Processing ",thisPlayer$Player, " (",round(counter*100/nrow(playersNew),1),"%)"))
if (thisPlayer$Age < 20) { # not enough players to compare to at age 19 or younger
thisPlayer$Age <- 20
}
if (thisPlayer$Age > 39) { # not enough players to compare to at age 41 or older
thisPlayer$Age <- 39
}
thisPlayerStats <- .predictPlayerWeighted(thisPlayer$Player) %>%
select(Player,Pos,Season,Age,everything())
if (nrow(thisPlayerStats)>0){ # in case thisPlayerStats return an empty data.frame
if (!is.na(thisPlayerStats$effPTS)){ # rosters not yet updated so include R (last season rookies)
#if (thisPlayer$Exp %in% c(seq(1,25,1),"R")){ # rosters not yet updated so include R (last season rookies)
print("NBA player: OK!")
print(thisPlayerStats)
} else if (player %in% playersNew$Player) { # NBA player that didn't play enough minutes so I use his numbers from last season as prediction
thisPlayerStats <- .team_preparePredict(filter(playersNew, Player == player),team) %>%
mutate(Age = Age + 1) %>%
select(Player,Pos,Season,Age,everything())
thisMin <- thisTeam %>% mutate(effMin = MP*G/(5*15*3936)) # Use 15 as an approximate roster size to account for effective minutes played for players with low total minutes
teamMinutes <- sum(thisMin$effMin)
thisMin <- #mutate(thisMin, effMin = effMin) %>%
filter(thisMin,Player == player) %>%
distinct(effMin) %>%
as.numeric()
thisPlayerStats <- mutate(thisPlayerStats, effMin = thisMin)
print("NBA player: Empty predicted stats!")
print(thisPlayerStats)
} else { # Rookie player or returns NA stats
# compute rookie player average stats for this player
thisPlayerStats <- .calculate_AvgPlayer(playersNew, thisPlayer$Age + 1) %>%
mutate(Player = as.character(thisPlayer$Player), Pos = as.character(thisPlayer$Pos),
G = as.numeric(thisPlayer$G), GS = as.numeric(thisPlayer$GS), Tm = team)
thisPlayerStats <- .team_preparePredict(data = thisPlayerStats, thisTeam = as.character(thisPlayer$Tm),singlePlayer = TRUE)
print("Average player: OK!")
print(thisPlayerStats)
#}
}
} else if (player %in% playersNew$Player) { # NBA player that didn't play enough minutes so I use his numbers from last season as prediction
thisPlayerStats <- .team_preparePredict(filter(playersNew, Player == player),team) %>%
mutate(Age = Age + 1) %>%
select(Player,Pos,Season,Age,everything())
print("NBA player: Short minutes!")
print(thisPlayerStats)
} else {
thisPlayerStats <- .calculate_AvgPlayer(playersNew, thisPlayer$Age + 1) %>%
mutate(Player = as.character(thisPlayer$Player), Pos = as.character(thisPlayer$Pos),
G = as.numeric(thisPlayer$G), GS = as.numeric(thisPlayer$GS), Tm = team, Age)
thisPlayerStats <- .team_preparePredict(data = thisPlayerStats, thisTeam = as.character(thisPlayer$Tm),singlePlayer = TRUE)
print("Average player: OK!")
print(thisPlayerStats)
}
if (nrow(thisTeamStats)>0){
thisTeamStats <- bind_rows(thisTeamStats,thisPlayerStats)
} else{
thisTeamStats <- thisPlayerStats
}
}
if (nrow(thisTeamStats) > 0) {
thisTeamStats <- mutate(thisTeamStats, Tm = team)
if (nrow(playersNewPredicted)>0){
playersNewPredicted <- bind_rows(playersNewPredicted,thisTeamStats)
} else{
playersNewPredicted <- thisTeamStats
}
}
}
playersNewPredicted <- distinct(playersNewPredicted, Player, Tm, .keep_all=TRUE)
limitMinutes <- 2*quantile(playersNewPredicted$effMin,.95) # control for possible outliers
defaultMinutes <- quantile(playersNewPredicted$effMin,.1) # assign low minutes to outliers as they most likely belong to players with very little playing time
playersNewPredicted2 <- mutate(playersNewPredicted,effMin = ifelse(effMin > limitMinutes, defaultMinutes,effMin))
write.csv(playersNewPredicted2, "data/playersNewPredicted_2020.csv", row.names = FALSE)
}
# pre-calculate tsne points for all players and seasons
write_tsne_points_All <- function(){
# data_tsne contains the input data for tSNE filtered and cleaned up
# from: data_tsne <- .tSNE_prepare_All() # for tSNE visualization from similarityFunctions.R
# calculate tsne-points Dimensionality reduction to 2-D
library(doMC) # use parallel processing on this machine through "foreach"
registerDoMC(2) # As far as I know my MAC works on 2 cores
library(Rtsne)
#data_tsne_sample <- dplyr::sample_n(data_tsne,1000)
data_tsne <- playersHist %>%
group_by(Player,Season) %>%
mutate(keep = ifelse(n() > 1, 1, 0)) %>%
filter(keep == 0 | Tm == "TOT") %>%
ungroup()
data_tsne_sample <- filter(data_tsne,Season > "1980-1981") %>%
select_if(is.numeric) %>%
select(-contains("."), -c(GS, TRB, PTS,keep)) %>%
as.matrix()
set.seed(42)
tsne_out <- Rtsne(data_tsne_sample, pca=FALSE, check_duplicates = FALSE,
perplexity=50, theta = 0.5, max_iter = 800) # Run TSNE
plot(tsne_out$Y, asp=1)
}
# write MVPs from past seasons
write_mvps <- function(){
library(httr)
library(rvest)
mvps <- data.frame(Player=NULL, Season=NULL)
for (thisSeason in 1980:as.numeric(thisYear)){
url <- paste0("https://www.basketball-reference.com/leagues/NBA_",
thisSeason,".html")
thisPlayer <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="meta"]/div[2]/p[2]/a') %>%
html_text()
thisMVP <- data.frame(Player = thisPlayer, Season = paste0(thisSeason-1,"-",thisSeason))
if (nrow(mvps) > 0) mvps <- rbind(mvps,thisMVP) else mvps <- thisMVP
}
write.csv(mvps, "data/mvps.csv", row.names = FALSE)
}
# compile league awards: mvp, def player, rookie of the year, etc.
write_Awards <- function(){ # Not working!
library(httr)
library(rvest)
awards <- data.frame(Player=NULL, Season=NULL, award=NULL)
for (thisSeason in 1980:as.numeric(thisYear)){
url <- paste0("https://www.basketball-reference.com/leagues/NBA_",
thisSeason,".html")
thisPlayer <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="div_all-nba"]') %>%
#html_children() %>%
#html_children() %>%
html_nodes('table')
thisAwards <- data.frame(Player = thisPlayer, Season = paste0(thisSeason-1,"-",thisSeason), award = )
if (nrow(awards) > 0) awards <- rbind(awards,thisAwards) else awards <- thisAwards
}
write.csv(mvps, "data/mvps.csv", row.names = FALSE)
}
# put together tsne_ready to load at the start of dashboards
# imports: tsne_points_All.csv
# calls helpers
write_tsne_ready_hist <- function() {
#source("helper_functions.R")
#.teamsPredictedPower()
tsne_points <- read.csv("data/tsne_points_All.csv",stringsAsFactors = FALSE)
# load data
data_tsne <- .tSNE_prepare_All() # for tSNE visualization from similarityFunctions.R
data_tsne_sample <- filter(data_tsne,Season > "1995-1996")
# tsne_points are pre-calculated from write_tSNE_All.R and saved in data/ directory
# using this function: tsne_points <- write_tSNE_compute_All()
if (!nrow(data_tsne_sample)==nrow(tsne_points)){ # in case labels and coordinates have different sizes
tsne_ready <- tsne_points
} else {
tsne_ready <- cbind(data_tsne_sample,tsne_points)
}
names(tsne_ready)[ncol(tsne_ready)-1] <- "x"
names(tsne_ready)[ncol(tsne_ready)] <- "y"
write.csv(tsne_ready, "data/tsne_ready_hist.csv", row.names = FALSE)
}
# precalculate t-SNE for predicted stats (new season)
# imports: playersNewPredicted_Final_adjMin.csv
write_tsne_points_newSeason <- function() {
require(tsne)
data_tsne_sample <- read.csv("data/playersNewPredicted_Final_adjMin.csv", stringsAsFactors = FALSE) %>%
select_if(is.numeric) %>% select(-one_of("Pick"))
if (nrow(data_tsne_sample)>0){
num_iter <- 600
max_num_neighbors <- 20
set.seed(456) # reproducitility
tsne_points <- tsne(data_tsne_sample,
max_iter=as.numeric(num_iter),
perplexity=as.numeric(max_num_neighbors),
epoch=100)
plot(tsne_points)
} else {
tsne_points <- c()
}
write.csv(tsne_points, "data/tsne_points_newSeason.csv",row.names = FALSE)
}
# put together tsne_ready predicted to load at start of dashboards
# imports: tsne_points_newSeason.csv and playersNewPredicted_Final_adjMin.csv
# calls helpers
write_tsne_ready_newSeason <- function(){
#source("helper_functions.R")
tsne_points <- read.csv("data/tsne_points_newSeason.csv",stringsAsFactors = FALSE)
# load data
data_tsne_sample <- read.csv("data/playersNewPredicted_Final_adjMin.csv", stringsAsFactors = FALSE) %>%
select_if(is.character)
# tsne_points are pre-calculated from write_tSNE_All.R and saved in data/ directory
# using this function: tsne_points <- write_tSNE_compute_All()
if (!nrow(data_tsne_sample)==nrow(tsne_points)){ # in case labels and coordinates have different sizes
tsne_ready <- tsne_points
} else {
tsne_ready <- cbind(data_tsne_sample,tsne_points)
}
names(tsne_ready)[ncol(tsne_ready)-1] <- "x"
names(tsne_ready)[ncol(tsne_ready)] <- "y"
write.csv(tsne_ready, "data/tsne_ready_newSeason.csv", row.names = FALSE)
}
write_tensorflow_proj_inputs <- function() {
playersHist <- read.csv("data/playersHist.csv", stringsAsFactors = FALSE)
data <- select_if(playersHist, is.numeric) %>%
select(-c(Age,GS,PTS), -contains("."))
metadata <- playersHist
#metadata <- select_if(playersHist, is.character)
write.table(data, "data/ts_data.csv", sep = "\t", row.names = FALSE, col.names = FALSE)
write.table(metadata, "data/ts_metadata.csv", sep = "\t", row.names = FALSE)
#metadata_edited <- read.table("data/metadata-edited.tsv", sep = "\t", stringsAsFactors = FALSE)
}
########## TEAMS ###########
# Write team stats by season.
# Imports: playersHist.csv
write_teamStats <- function(what_season = thisYear) {
require(httr)
require(tidyverse)
library(rvest)
thisYear <- substr(Sys.Date(),1,4)
playersHist <- read.csv("data/playersHist.csv", stringsAsFactors = FALSE)
### Return data starting from input season
firstYear <- as.numeric(what_season)
# Read teams stats for all seasons
teamStats <- data.frame()
lastSeason <- as.numeric(substr(max(as.character(playersHist$Season)),1,4))
for (year in firstYear:as.numeric(thisYear)){
url <- paste0("http://www.basketball-reference.com/leagues/NBA_",year,".html")
# Eastern conference
thisSeasonStats <- url %>%
read_html() %>%
#html_nodes(xpath='//*[@id="all_standings"]/table') %>%
html_nodes(xpath='//*[@id="confs_standings_E"]') %>%
html_table(fill = TRUE)
thisSeasonStats_E <- thisSeasonStats[[1]]
names(thisSeasonStats_E)[1] <- "Team"
# Western conference
thisSeasonStats <- url %>%
read_html() %>%
#html_nodes(xpath='//*[@id="all_standings"]/table') %>%
html_nodes(xpath='//*[@id="confs_standings_W"]') %>%
html_table(fill = TRUE)
thisSeasonStats_W <- thisSeasonStats[[1]]
names(thisSeasonStats_W)[1] <- "Team"
# All together
thisSeasonStats <- bind_rows(thisSeasonStats_E,thisSeasonStats_W)
#thisSeasonStats <- thisSeasonStats[2:nrow(thisSeasonStats),1:8]
#names(thisSeasonStats) <- c("Team",thisSeasonStats[1,2:ncol(thisSeasonStats)])
#thisSeasonStats <- thisSeasonStats[-1,]
#thisSeasonStats <- thisSeasonStats[!(thisSeasonStats$W=="W"),]
#thisSeasonStats <- thisSeasonStats[!grepl("division",tolower(thisSeasonStats[,1])),]
thisSeasonStats <- select(thisSeasonStats, -`W/L%`, -GB)
thisSeasonStats <- mutate_if(thisSeasonStats, is.numeric, funs(as.numeric))
thisSeasonStats$Team <- gsub("\\*?\\([0-9]+\\)","",thisSeasonStats$Team)
thisSeasonStats$Team <- gsub("*","",thisSeasonStats$Team,fixed = TRUE)
thisSeasonStats$Team <- trimws(thisSeasonStats$Team)
names(thisSeasonStats) <- gsub("PS/G","PTS",names(thisSeasonStats))
names(thisSeasonStats) <- gsub("PA/G","PTSA",names(thisSeasonStats))
# trim <- gsub("\\*?\\([0-9]+\\)","",thisSeasonStats$Team)
# trim <- gsub("*","",trim,fixed = TRUE)
# blank <- substr(trim[1],nchar(trim[1]),nchar(trim[1]))
# trim <- gsub(blank,"",trim)
# thisSeasonStats$Team <- trim
thisSeasonStats$Season <- paste0(year-1,"-",year)
if (nrow(teamStats)>0) {
teamStats <- bind_rows(teamStats,thisSeasonStats)
} else {
teamStats <- thisSeasonStats
}
}
# remove strange characters
teamStats$Team <- gsub(" ","",teamStats$Team)
# append to existing file when last year is selected
if (firstYear==thisYear) {
teamStatsOLD <- read.csv("data/teamStats.csv", stringsAsFactors = FALSE)
# in case this script is run several times don't want to duplicate records
if (max(teamStats$Season) > max(teamStatsOLD$Season)) {
teamStats <- bind_rows(teamStatsOLD,teamStats)
}
}
write.csv(teamStats, "data/teamStats.csv",row.names = FALSE)
}
# compute tsne for teams
# imports: playersNewPredicted_Final_adjPer.csv
# calls helpers
write_tsne_points_teams <- function(){
require(tsne)
playersPredictedStats_adjPer <- read.csv("data/playersNewPredicted_Final_adjPer.csv", stringsAsFactors = FALSE)
teamStats <- .computeTeamStats(data = playersPredictedStats_adjPer)
data_tsne_sample <- teamStats %>%
select_if(is.numeric) %>%
mutate_all(function(x) (x-min(x))/(max(x)-min(x)))
if (nrow(data_tsne_sample)>0){
num_iter <- 1500
max_num_neighbors <- 2
set.seed(456) # reproducitility
tsne_points <- tsne(data_tsne_sample,
max_iter=as.numeric(num_iter),
perplexity=as.numeric(max_num_neighbors),
epoch=100)
plot(tsne_points)
} else {
tsne_points <- c()
}
write.csv(tsne_points, "data/tsne_points_teams.csv",row.names = FALSE)
}
# put together tsne_ready predicted to load at start of dashboards
# imports: tsne_points_teams.csv and playersNewPredicted_Final_adjPer.csv
# calls helpers
write_tsne_ready_teams <- function(){
#source("helper_functions.R")
tsne_points <- read.csv("data/tsne_points_teams.csv",stringsAsFactors = FALSE)
# load data
playersPredictedStats_adjPer <- read.csv("data/playersNewPredicted_Final_adjPer.csv", stringsAsFactors = FALSE)
data_tsne_sample <- .computeTeamStats(data = playersPredictedStats_adjPer) %>%
select_if(is.character)
# tsne_points are pre-calculated from write_tSNE_All.R and saved in data/ directory
# using this function: tsne_points <- write_tSNE_compute_All()
if (!nrow(data_tsne_sample)==nrow(tsne_points)){ # in case labels and coordinates have different sizes
tsne_ready <- tsne_points
} else {
tsne_ready <- cbind(data_tsne_sample,tsne_points)
}
names(tsne_ready)[ncol(tsne_ready)-1] <- "x"
names(tsne_ready)[ncol(tsne_ready)] <- "y"
write.csv(tsne_ready, "data/tsne_ready_teams.csv", row.names = FALSE)
}
########## ROOKIES ###########
# Historical drafted rookies
write_rookiesHist <- function(){
lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
firstDraft <- 1979
rookiesHist <- data.frame()
for (draftYear in firstDraft:lastDraft) {
url <- paste0("http://www.basketball-reference.com/draft/NBA_",draftYear,".html")
thisSeasonDraft <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisSeasonDraft <- thisSeasonDraft[[1]]
names(thisSeasonDraft) <- thisSeasonDraft[1,]
thisSeasonDraft <- as.data.frame(thisSeasonDraft[-1,])
thisSeasonDraft <- thisSeasonDraft[,1:10]
thisSeasonDraft <- dplyr::select(thisSeasonDraft, Pick = Pk, Team = Tm, Player, College)
thisSeasonDraft <- thisSeasonDraft[which(!(thisSeasonDraft$Pick=="" | thisSeasonDraft$Pick=="Pk")),]
thisSeasonDraft <- mutate(thisSeasonDraft, Season = draftYear)
if (nrow(rookiesHist)>0){
rookiesHist <- bind_rows(rookiesHist,thisSeasonDraft)
} else{
rookiesHist <- thisSeasonDraft
}
}
write.csv(rookiesHist, "data/rookiesHist.csv",row.names = FALSE)
}
# writer college players historical data
write_collegePlayersHist <- function(col_G = 15,num_pages = 30,firstDraft = 1994,lastDraft=2018){
# Read stats from college players and match to drafted players
# query college players who played at least col_G games. Min per games not recorded before 2009
#col_G <- 15
#num_pages <- 30
# First 100 sorted desc by Total Points:
# http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=1994&year_max=1994&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=15&c2stat=&c2comp=gt&c2val=&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=pts
# subsequent players in batches of 100:
# http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=1994&year_max=1994&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_fg=Y&pos_is_f=Y&pos_is_fc=Y&pos_is_cf=Y&pos_is_c=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=15&c2stat=&c2comp=gt&c2val=&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=pts&order_by_asc=&offset=100
#lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
#firstDraft <- 1994
collegePlayersHist <- data.frame()
for (season in (firstDraft-1):(lastDraft-1)){
print(paste0("Processing season: ",season))
url <- paste0("http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=",
season,"&year_max=",season,"&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=",
col_G,"&c2stat=&c2comp=gt&c2val=&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=pts")
thisCollege <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisCollege <- thisCollege[[1]]
names(thisCollege) <- thisCollege[1,]
thisCollege <- thisCollege[-1,]
collegePlayers <- thisCollege[which(!(thisCollege$Rk=="" | thisCollege$Rk=="Rk")),]
collegePlayers$Rk <- as.numeric(collegePlayers$Rk)
for (page in 1:(num_pages-1)){ # read a total of num_pages*100 college players
print(paste0("Processing page: ",page))
url <- paste0("http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=",
season,"&year_max=",season,"&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=",
col_G,"&c2stat=&c2comp=gt&c2val=&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=pts&order_by_asc=&offset=",
page*100)
thisCollege <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisCollege <- thisCollege[[1]]
names(thisCollege) <- thisCollege[1,]
thisCollege <- thisCollege[-1,]
thisCollege <- thisCollege[which(!(thisCollege$Rk=="" | thisCollege$Rk=="Rk")),]
thisCollege$Rk <- as.numeric(thisCollege$Rk)
collegePlayers <- rbind(collegePlayers,thisCollege)
}
collegePlayers <- mutate(collegePlayers, Season = season)
names(collegePlayers) <- gsub("2","X2",names(collegePlayers))
names(collegePlayers) <- gsub("3","X3",names(collegePlayers))
if (nrow(collegePlayersHist)>0){
collegePlayersHist <- rbind(collegePlayersHist,collegePlayers)
} else{
collegePlayersHist <- collegePlayers
}
}
write.csv(collegePlayersHist, "data/collegePlayersHist.csv", row.names = FALSE)
}
# Merge drafted players with college players.
# Imports rookiesHist.csv and collegePlayersHist.csv
write_rookieStatsHist <- function(){
rookiesHist <- read.csv("data/rookiesHist.csv", stringsAsFactors = FALSE)
collegePlayersHist <- read.csv("data/collegePlayersHist.csv", stringsAsFactors = FALSE)
rookieStatsHist <- merge(rookiesHist, collegePlayersHist, by = c("Player","Season"))
write.csv(rookieStatsHist, "data/rookieStatsHist.csv", row.names = FALSE)
}
# computes tsne for rookies
# uses helper .tSNE_prepareRookies()
write_tsne_pointsRookies <- function(){
num_iter <- 400
max_num_neighbors <- 10
data_tsne <- .tSNE_prepareRookies()
# calculate tsne-points Dimensionality reduction to 2-D
if (nrow(data_tsne)>0){
set.seed(456) # reproducitility
tsne_points <- tsne(data_tsne[,-c(1:3)],
max_iter=as.numeric(num_iter),
perplexity=as.numeric(max_num_neighbors),
epoch=num_iter)
} else {
tsne_points <- c()
}
write.csv(tsne_points, "data/tsne_pointsRookies.csv",row.names = FALSE)
}
# write rookies from last draft
write_rookiesDraft <- function(){
rookies <- data.frame()
lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
url <- paste0("http://www.basketball-reference.com/draft/NBA_",lastDraft,".html")
thisSeasonDraft <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisSeasonDraft <- thisSeasonDraft[[1]]
names(thisSeasonDraft) <- thisSeasonDraft[1,]
thisSeasonDraft <- as.data.frame(thisSeasonDraft[-1,])
rookies <- thisSeasonDraft[,1:10]
rookies <- dplyr::select(rookies, Pick = Pk, Team = Tm, Player, College)
rookies <- rookies[which(!(rookies$Pick=="" | rookies$Pick=="Pk")),]
# Correct spelling errors 2016 draft
# rookies[grepl("Chris",rookies$Player),]$Player <- "Marquese Chriss"
# rookies[grepl("Dami",rookies$Player),]$Player <- "Damian Jones"
# rookies[grepl("Zimmerm",rookies$Player),]$Player <- "Stephen Zimmerman Jr."
write.csv(rookies, "data/rookiesDraft.csv",row.names = FALSE)
}
# write historical drafts
write_rookiesDraftHist <- function(){
rookiesDraftHist <- data.frame()
lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
for (d in (lastDraft-20):lastDraft) {
url <- paste0("http://www.basketball-reference.com/draft/NBA_",d,".html")
require(httr)
require(rvest)
thisSeasonDraft <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisSeasonDraft <- thisSeasonDraft[[1]]
names(thisSeasonDraft) <- thisSeasonDraft[1,]
thisSeasonDraft <- as.data.frame(thisSeasonDraft[-1,])
rookies <- thisSeasonDraft[,1:10]
rookies <- dplyr::select(rookies, Pick = Pk, Team = Tm, Player, College)
rookies <- rookies[which(!(rookies$Pick=="" | rookies$Pick=="Pk")),]
rookies <- mutate(rookies, Year = as.character(d))
if (nrow(rookiesDraftHist)>0) {
rookiesDraftHist <- rbind(rookiesDraftHist,rookies)
} else {
rookiesDraftHist <- rookies
}
}
write.csv(rookiesDraftHist, "data/rookiesDraftHist.csv",row.names = FALSE)
}
# write all rookies (all draft rounds and non drafted)
write_rookies <- function(){
rookies <- data.frame()
newSeason <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 2
teamList <- unique(filter(playersHist,Season == paste0(newSeason-2,"-",newSeason-1))$Tm)
teamList <- teamList[which(!(teamList == "TOT"))]
for (team in teamList) {
url <- paste0("http://www.basketball-reference.com/teams/",team,"/",newSeason,".html")
#https://www.basketball-reference.com/teams/NYK/2018.html
thisSeasonRookies <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="roster"]') %>%
html_table(fill = TRUE)
thisSeasonRookies <- thisSeasonRookies[[1]]
thisSeasonRookies <- thisSeasonRookies[,names(thisSeasonRookies)[which(nchar(names(thisSeasonRookies))>0)]]
thisRookies <- filter(thisSeasonRookies, Exp == "R")
thisRookies <- mutate(thisRookies,
Age = newSeason - as.numeric(substr(`Birth Date`,nchar(`Birth Date`)-4,nchar(`Birth Date`))))
thisRookies <- dplyr::select(thisRookies, Player, Age, College) %>%
mutate(Tm = team)
if (nrow(rookies)>0) {
rookies <- rbind(rookies, thisRookies)
} else {
rookies <- thisRookies
}
}
write.csv(rookies, "data/rookies.csv",row.names = FALSE)
}
# write college players stats from last season
# imports playersHist.csv
write_collegePlayers <- function(){
# Read stats from college players and match to drafted players
# query college players who played at least col_G games and col_MP min/game last season
from <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) - 1
to <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
collegePlayers <- data.frame()
#for (lastDraft in from:to){
col_G <- 15
col_MP <- 7
num_pages <- 90
# First 100 sorted desc by PER:
# http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=2016&year_max=2016&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_fg=Y&pos_is_f=Y&pos_is_fc=Y&pos_is_cf=Y&pos_is_c=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=25&c2stat=mp_per_g&c2comp=gt&c2val=20&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=per
# subsequent players in batches of 100:
# http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=2016&year_max=2016&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_fg=Y&pos_is_f=Y&pos_is_fc=Y&pos_is_cf=Y&pos_is_c=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=25&c2stat=mp_per_g&c2comp=gt&c2val=20&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=per&order_by_asc=&offset=100
#collegePlayers <- data.frame()
#lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
url <- paste0("http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=",
from,"&year_max=",to,"&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_fg=Y&pos_is_f=Y&pos_is_fc=Y&pos_is_cf=Y&pos_is_c=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=",
col_G,"&c2stat=mp_per_g&c2comp=gt&c2val=",col_MP,"&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=per")
thisCollege <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisCollege <- thisCollege[[1]]
names(thisCollege) <- thisCollege[1,]
thisCollege <- thisCollege[-1,]
collegePlayers <- thisCollege[which(!(thisCollege$Rk=="" | thisCollege$Rk=="Rk")),]
for (page in 1:(num_pages-1)){ # read a total of num_pages*100 college players
print(paste0("processing year: ",lastDraft, " page: ",page))
url <- paste0("http://www.sports-reference.com/cbb/play-index/psl_finder.cgi?request=1&match=single&year_min=",
from,"&year_max=",to,"&conf_id=&school_id=&class_is_fr=Y&class_is_so=Y&class_is_jr=Y&class_is_sr=Y&pos_is_g=Y&pos_is_gf=Y&pos_is_fg=Y&pos_is_f=Y&pos_is_fc=Y&pos_is_cf=Y&pos_is_c=Y&games_type=A&qual=&c1stat=g&c1comp=gt&c1val=",
col_G,"&c2stat=mp_per_g&c2comp=gt&c2val=",col_MP,"&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=per&order_by_asc=&offset=",
page*100)
thisCollege <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="stats"]') %>%
html_table(fill = TRUE)
thisCollege <- thisCollege[[1]]
names(thisCollege) <- thisCollege[1,]
thisCollege <- thisCollege[-1,]
thisCollege <- thisCollege[which(!(thisCollege$Rk=="" | thisCollege$Rk=="Rk")),]
collegePlayers <- bind_rows(collegePlayers,thisCollege)
}
write.csv(collegePlayers, "data/collegePlayers.csv", row.names = FALSE)
}
# Merge drafted players with college players
# imports: rookies.csv and collegePlayers.csv
write_rookieStats_europePlayers <- function(){
rookies <- read.csv("data/rookies.csv", stringsAsFactors = FALSE) # from writeAllRookies
collegePlayers <- read.csv("data/collegePlayers.csv", stringsAsFactors = FALSE) %>% # from write_CollegePlayers
group_by(Player) %>%
summarise_if(is.numeric, mean)
# Correct spelling errors 2017 draft
# collegePlayers[grepl("Nazareth Mitrou-Long",collegePlayers$Player),]$Player <- "Naz Mitrou-Long"
# collegePlayers[grepl("Royce O'Neale",collegePlayers$Player),]$Player <- "Royce O'Neal"
# collegePlayers[grepl("Jacorey Williams",collegePlayers$Player),]$Player <- "JaCorey Williams"
# collegePlayers[grepl("Andrew White III",collegePlayers$Player),]$Player <- "Andrew White"
# collegePlayers[grepl("TJ Leaf",collegePlayers$Player),]$Player <- "T.J. Leaf"
# collegePlayers[grepl("Frank Mason",collegePlayers$Player),]$Player <- "Frank Mason III"
# collegePlayers[grepl("Akim Mitchell",collegePlayers$Player),]$Player <- "Akil Mitchell"
#collegePlayers[grepl("Dennis Smith",collegePlayers$Player),]$Player <- "Dennis Smith Jr."
#ollegePlayers[grepl("Leaf",collegePlayers$Player),]$Player <- "TJ Leaf"
rookieStats <- merge(rookies, collegePlayers, by = "Player",all.x=TRUE) %>%
mutate(Age = as.character(Age)) %>%
group_by(Player) %>% summarise_if(is.numeric,funs(mean(.,na.rm=TRUE))) %>%
left_join(rookies, c("Player"="Player")) %>%
mutate(Age = as.numeric(Age))
lastDraft <- as.numeric(substr(max(as.character(playersHist$Season)),1,4)) + 1
rookieReady <- filter(rookieStats, !is.nan(G)) %>% select(one_of(names(playersHist)),College) %>%
mutate(Season = lastDraft)
rookieLeftout <- filter(rookieStats, is.nan(G)) %>% select(Player,Age,College,Tm)
#billy-yakuba-ouattara
# Find stats from european players drafted
europePlayers <- data.frame()
require(httr)
for (i in 1:nrow(rookieLeftout)){
if (rookieLeftout$College[i]==""){
thisPlayer <- as.character(rookieLeftout$Player[i])
name_edited <- tolower(thisPlayer)
name_edited <- gsub(" ","-",name_edited)
url <- paste0("https://www.basketball-reference.com/euro/players/",name_edited,"-1.html")
table_type <- "ALL" # ALL,EUR,CLU
if (status_code(GET(url))==200){ #european player
thisEurope <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="per_gameALL0"]') %>%
html_table(fill = TRUE)
if (length(thisEurope)==0){ # try euroleague stats if total are unavailable
thisEurope <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="per_gameEUR0"]') %>%
html_table(fill = TRUE)
table_type <- "EUR"
}
if (length(thisEurope)==0){ # try club stats if total or euroleague are unavailable
thisEurope <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="per_gameCLU0"]') %>%
html_table(fill = TRUE)
table_type <- "CLU"
}
if (length(thisEurope)>0){
rookieLeftout$College[i] <- "Europe"
thisEurope <- thisEurope[[1]]
print(paste0("Processing: ",thisPlayer))
if (table_type == "CLU") names(thisEurope)[4] <- "Country"
thisEurope <- thisEurope %>%
filter(G == max(G)) %>%
select(-contains("Club"), -contains("Country")) %>%
mutate(Player = thisPlayer) %>%
head(1)
thisEurope$Tm <- rookieLeftout$Tm[i]
thisEurope$College <- rookieLeftout$College[i]
thisEurope$Age <- rookieLeftout$Age[i]
europePlayers <- rbind(europePlayers,thisEurope)
} else { # international or european without stats
rookieLeftout$College[i] <- "International"
}
} else { # college player that didn't find a match in collegePlayers. Find the reason!
rookieLeftout$College[i] <- "International"
}
}
}
rookieLeftout <- filter(rookieLeftout, !(College == "Europe")) %>% select(Player,Age,College,Tm)
rookieLeftout$Season <- lastDraft
# For international players or non-matched college players use averages of their respective groups for their stats
averageCollegeRookie <- rookieReady %>%
summarise_if(is.numeric, function(x) mean(x,na.rm = TRUE)) %>%
select(-Season)
names(europePlayers) <- gsub("%",".",names(europePlayers), fixed = TRUE)
names(europePlayers) <- gsub("2","X2",names(europePlayers),fixed = TRUE)
names(europePlayers) <- gsub("3","X3",names(europePlayers),fixed = TRUE)
europePlayers <- select(europePlayers, Player, everything(),
-c(`League(s)`,FG.,X3P.,X2P.,FT.))
averageEuropeRookie <- europePlayers %>%
summarise_if(is.numeric,function(x) mean(x,na.rm = TRUE))
rookieLeftoutStats <- data.frame()
for (i in 1:nrow(rookieLeftout)) {
if (rookieLeftout$College[i] == "International") {
thisRookie <- cbind(rookieLeftout[i,],averageEuropeRookie)
} else {
thisRookie <- cbind(rookieLeftout[i,],averageCollegeRookie)
}
rookieLeftoutStats <- bind_rows(rookieLeftoutStats,thisRookie)
}
rookieReady <- select(rookieReady, -Season)
rookieLeftoutStats <- select(rookieLeftoutStats, -Season)
europePlayers <- select(europePlayers, -Season)
rookieStatsFinal <- bind_rows(rookieReady,rookieLeftoutStats,europePlayers) %>%
mutate(FG. = ifelse(FGA == 0,0,FG/FGA), X3P. = ifelse(X3PA == 0,0,X3P/X3PA),
X2P. = ifelse(X2PA == 0,0,X2P/X2PA), FT. = ifelse(FTA == 0,0,FT/FTA),
Season = paste0(lastDraft,"-",lastDraft+1)) %>%
mutate(Age = as.integer(Age))
write.csv(rookieStatsFinal, "data/rookieStats.csv", row.names = FALSE)
write.csv(europePlayers, "data/europePlayers.csv", row.names = FALSE)
}
# Once per game stats have been compiled for all rookies (college and international) compute their
# per-minute stats
# imports rookieStats.csv
write_rookieEfficientStats <- function() {
rookieStats <- read.csv("data/rookieStats.csv", stringsAsFactors = FALSE)
# In college and Europe they play 40-min game. I will calculate their pre-minute stats
# based on a 48-min game as the "price" for being a rookie in the NBA
rookieEffStats <- rookieStats %>%
group_by(Player) %>%
mutate(effMin = MP/3936, effFG = FG/(3936*effMin),
effFGA = FGA/(3936*effMin),eff3PM = X3P/(3936*effMin),eff3PA = X3PA/(3936*effMin),
eff2PM = X2P/(3936*effMin),eff2PA = X2PA/(3936*effMin),
effFTM = FT/(3936*effMin),effFTA = FTA/(3936*effMin),
effORB = ORB/(3936*effMin),effDRB = DRB/(3936*effMin),
effTRB = TRB/(3936*effMin),effAST = AST/(3936*effMin),
effSTL = STL/(3936*effMin),effBLK = BLK/(3936*effMin),
effTOV = TOV/(3936*effMin),effPF = PF/(3936*effMin),
effPTS = PTS/(3936*effMin)) %>%
dplyr::select(Player,Age,Season,Tm,FGPer = FG.,FG3Per = X3P., FG2Per = X2P., effFGPer = eFG.,
FTPer = FT., starts_with("eff"),
-G,-MP,FG,-FGA,-X3P,-X3PA,-X2P,-X2PA,-FG,-FTA,-ORB,-DRB,-TRB,-AST,
-BLK,-TOV,-PF,-FT,-STL,-PTS)
# Impute NAs by 0. If NA means no shot attempted, ie,
# either the player didn't play enough time or is really bad at this particular type of shot.
for (i in 5:ncol(rookieEffStats)){
rookieEffStats[is.na(rookieEffStats[,i]),i] <- 0
}
rookieEffStats <- as.data.frame(rookieEffStats)
write.csv(rookieEffStats, "data/rookieEfficientStats.csv", row.names = FALSE)
}
# Once per game stats have been compiled for all college players compute their
# per-minute stats
# imports collegePlayers.csv
write_collegeEfficientStats <- function() {
collegePlayers <- read.csv("data/collegePlayers.csv", stringsAsFactors = FALSE)
# In college and Europe they play 40-min game. I will calculate their pre-minute stats
# based on a 48-min game as the "price" for being a rookie in the NBA
collegeEffStats <- collegePlayers %>%
group_by(Player) %>%
mutate(Age = ifelse(Class == "SR", 22, ifelse(Class == "JR", 21, ifelse(Class == "SO", 20, 19)))) %>%
summarise_if(is.numeric, mean) %>%
mutate(Age = ceiling(Age), effMin = MP/3936, effFG = FG/(3936*effMin),
effFGA = FGA/(3936*effMin),eff3PM = X3P/(3936*effMin),eff3PA = X3PA/(3936*effMin),
eff2PM = X2P/(3936*effMin),eff2PA = X2PA/(3936*effMin),
effFTM = FT/(3936*effMin),effFTA = FTA/(3936*effMin),
effORB = ORB/(3936*effMin),effDRB = DRB/(3936*effMin),
effTRB = TRB/(3936*effMin),effAST = AST/(3936*effMin),
effSTL = STL/(3936*effMin),effBLK = BLK/(3936*effMin),
effTOV = TOV/(3936*effMin),effPF = PF/(3936*effMin),
FGPer = FG/FGA,FG3Per = X3P/X3PA, FG2Per = X2P/X2PA,FTPer = FT/FTA,
effPTS = PTS/(3936*effMin)) %>%
dplyr::select(Player,Age,effFGPer = eFG.,
starts_with("eff"),
-G,-MP,FG,-FGA,-X3P,-X3PA,-X2P,-X2PA,-FG,-FTA,-ORB,-DRB,-TRB,-AST,
-BLK,-TOV,-PF,-FT,-STL,-PTS)
# Impute NAs by 0. If NA means no shot attempted, ie,
# either the player didn't play enough time or is really bad at this particular type of shot.
for (i in 5:ncol(collegeEffStats)){
collegeEffStats[is.na(collegeEffStats[,i]),i] <- 0
}
collegeEffStats <- as.data.frame(collegeEffStats)
write.csv(collegeEffStats, "data/collegeEffStats.csv", row.names = FALSE)
}
########## SEASON ###########
# Real season schedule from basketball-reference
write_realSeasonSchedule <- function(){
library(httr)
library(rvest)
# If not new data yet (transfers not finished so teams rosters not final), -----------------------------------------