forked from mhbw/evolving-hockey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EH_scrape_functions.R
4525 lines (3699 loc) · 171 KB
/
EH_scrape_functions.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
###################################################################################
##### Evolving-Hockey Scraper || 2019-05-18 #####
###################################################################################
## Current as of: R version 3.6.0 (2019-04-26)
## Dependencies
# library(RCurl); library(xml2); library(rvest); library(jsonlite); library(foreach)
# library(lubridate)
# library(tidyverse) -- specifically: stringr, readr, tidyr, and dplyr
## Set for numeric/text formatting within scraper
options(
scipen = 999,
stringsAsFactors = FALSE
)
## *** Notes & examples provided below all functions
## --------------- ##
## Source URLs ##
## --------------- ##
#####################
## HTML main source:
# events source: http://www.nhl.com/scores/htmlreports/20182019/PL020001.HTM
# rosters source: http://www.nhl.com/scores/htmlreports/20182019/RO020001.HTM
# shifts source (home): http://www.nhl.com/scores/htmlreports/20182019/TH020001.HTM
# shifts source (away): http://www.nhl.com/scores/htmlreports/20182019/TV020001.HTM
## HTML extras:
# game summary: http://www.nhl.com/scores/htmlreports/20182019/GS020001.HTM
# event summary: http://www.nhl.com/scores/htmlreports/20182019/ES020001.HTM
## NHL API:
# events source: https://statsapi.web.nhl.com/api/v1/game/2018020001/feed/live?site=en_nhl
# shifts source: http://www.nhl.com/stats/rest/shiftcharts?cayenneExp=gameId=2018020001
# shifts charts: http://www.nhl.com/stats/shiftcharts?id=2018020001 *** (for viewing)
# schedule source: https://statsapi.web.nhl.com/api/v1/schedule?startDate=2018-10-03&endDate=2018-10-03
## ESPN links:
# ESPN game IDs source: http://www.espn.com/nhl/scoreboard?date=20181003
# ESPN XML source: http://www.espn.com/nhl/gamecast/data/masterFeed?lang=en&isAll=true&rand=0&gameId=401044320
# ESPN events check: http://www.espn.com/nhl/playbyplay/_/gameId/401044320
#####################
## ------------------ ##
## Create Objects ##
## ------------------ ##
########################
## Dead NHL games (html source)
dead_games <- c(
"2007020011", "2007021178",
"2008020259", "2008020409", "2008021077", "2008030311",
"2009020081", "2009020658", "2009020885",
"2010020124"
)
## Create Team IDs (to use for API team triCodes)
Team_ID <-
data.frame(
Team =
c("N.J", "NYI", "NYR", "PHI", "PIT", "BOS", "BUF", "MTL", "OTT", "TOR", "ATL", "CAR", "FLA", "T.B",
"WSH", "CHI", "DET", "NSH", "STL", "CGY", "COL", "EDM", "VAN", "ANA", "DAL", "L.A", "ARI", "S.J",
"CBJ", "MIN", "WPG", "ARI", "VGK"
),
ID = c(seq(1:33))
) %>%
mutate(ID = ifelse(ID == 31, 52,
ifelse(ID == 32, 53,
ifelse(ID == 33, 54, ID))))
## For identifying event_team in HTM events
Team_ID_vec <- c(
"ANA", "ARI", "BOS", "BUF", "CAR", "CBJ", "CGY", "CHI", "COL", "DAL", "DET", "EDM", "FLA", "L.A", "MIN",
"MTL", "N.J", "NSH", "NYI", "NYR", "OTT", "PHI", "PIT", "S.J", "STL", "T.B", "TOR", "VAN", "WPG", "WSH",
"PHX", "ATL", "VGK", "L.V"
)
full_team_names <-
data.frame(
fullTeam =
c("ANAHEIM DUCKS", "ARIZONA COYOTES", "ATLANTA THRASHERS", "BOSTON BRUINS", "BUFFALO SABRES", "CALGARY FLAMES", "CAROLINA HURRICANES",
"CHICAGO BLACKHAWKS", "COLORADO AVALANCHE", "COLUMBUS BLUE JACKETS", "DALLAS STARS", "DETROIT RED WINGS", "EDMONTON OILERS",
"FLORIDA PANTHERS", "LOS ANGELES KINGS", "MINNESOTA WILD", "MONTREAL CANADIENS", "CANADIENS MONTREAL", "NASHVILLE PREDATORS", "NEW JERSEY DEVILS",
"NEW YORK ISLANDERS", "NEW YORK RANGERS", "OTTAWA SENATORS", "PHILADELPHIA FLYERS", "PHOENIX COYOTES", "PITTSBURGH PENGUINS", "SAN JOSE SHARKS",
"ST. LOUIS BLUES", "TAMPA BAY LIGHTNING", "TORONTO MAPLE LEAFS", "VANCOUVER CANUCKS", "VEGAS GOLDEN KNIGHTS", "WASHINGTON CAPITALS",
"WINNIPEG JETS"
),
Team =
c("ANA", "ARI", "ATL", "BOS", "BUF", "CGY", "CAR", "CHI", "COL", "CBJ", "DAL", "DET", "EDM", "FLA", "L.A",
"MIN", "MTL", "MTL", "NSH", "N.J", "NYI", "NYR", "OTT", "PHI", "ARI", "PIT", "S.J", "STL", "T.B", "TOR", "VAN", "VGK", "WSH", "WPG"
),
partTeam =
c("DUCKS", "COYOTES", "THRASHERS", "BRUINS", "SABRES", "FLAMES", "HURRICANES",
"BLACKHAWKS", "AVALANCHE", "BLUE JACKETS", "STARS", "RED WINGS", "OILERS",
"PANTHERS", "KINGS", "WILD", "CANADIENS", "MONTREAL", "PREDATORS", "DEVILS",
"ISLANDERS", "RANGERS", "SENATORS", "FLYERS", "COYOTES", "PENGUINS", "SHARKS",
"BLUES", "LIGHTNING", "MAPLE LEAFS", "CANUCKS", "GOLDEN KNIGHTS", "CAPITALS",
"JETS"
)
)
## ESPN's team IDs & event type codes
ESPN_team_IDs <-
data.frame(
team_ID =
as.numeric(c(
"25", "24", "1", "2", "7", "29", "3", "4", "17", "9", "5", "6", "26", "8",
"30", "10", "11", "27", "12", "13", "14", "15", "16", "18", "19", "20", "21",
"22", "37", "28", "23"
)),
Team =
c("ANA", "ARI", "BOS", "BUF", "CAR", "CBJ", "CGY", "CHI", "COL", "DAL", "DET", "EDM", "FLA",
"L.A", "MIN", "MTL", "N.J", "NSH", "NYI", "NYR", "OTT", "PHI", "PIT", "S.J", "STL", "T.B",
"TOR", "VAN", "VGK", "WPG", "WSH"
)
)
ESPN_codes <-
data.frame(
event =
c("FAC", "HIT", "GvTk", "GOAL", "SHOT", "MISS", "BLOCK", "PENL","STOP", "PRDY", "PSTR", "PEND",
"PERD", "SOC", "GEND", "SOut","error", "TAKE", "GIVE", "early intermission", "nothing", "nothing"
),
code =
as.character(c(
502, 503, 504, 505, 506, 507, 508, 509, 516, 517, 518, 519, 520, 521, 522, 0, 9999,
1401, 1402, -2147483648, 1, 5
))
)
## Other objects
sc.main_events <- c("GOAL", "SHOT", "MISS", "BLOCK", "HIT", "GIVE", "TAKE", "FAC", "PENL")
st.shot_events <- c("SHOT", "GOAL")
st.fenwick_events <- c("SHOT", "GOAL", "MISS")
st.corsi_events <- c("SHOT", "GOAL", "MISS", "BLOCK" )
st.strength_states <- c("3v3", "5v5", "4v4", "5v4", "4v5", "5v3", "3v5", "4v3", "3v4", "5vE", "Ev5", "4vE", "Ev4", "3vE", "Ev3") %>% as.factor()
st.even_strength <- c("5v5", "4v4", "3v3") %>% as.factor()
st.pp_strength <- c("5v4", "4v5", "5v3", "3v5", "4v3", "3v4") %>% as.factor()
st.empty_net <- c("5vE", "Ev5", "4vE", "Ev4", "3vE", "Ev3") %>% as.factor()
## Functions
na_if_null <- function(x) {
return(
ifelse(is.null(x), NA, x)
)
}
########################
## --------------------- ##
## Scraper Functions ##
## --------------------- ##
###########################
## --------------- ##
## Scrape Data ##
## --------------- ##
## Scrape Schedule
sc.scrape_schedule <- function(start_date, end_date, print_sched = TRUE) {
## getURL for schedule data
url_schedule <- NULL
try_count <- 3
while (!is.character(url_schedule) & try_count > 0) {
url_schedule <- try(
getURL(
paste0(
"https://statsapi.web.nhl.com/api/v1/schedule?startDate=",
as.character(start_date),
"&endDate=",
as.character(end_date)
)
)
)
try_count <- try_count - 1
}
## Parse JSON data
if (is.character(url_schedule)) {
schedule_list <- jsonlite::fromJSON(url_schedule)
}
## Return from function if scrape returned no data
if (length(schedule_list$dates) == 0) {
warning("NHL Schedule API Returned No Data")
## Return empty data.frame in same format if error occurred
return(
data.frame(
game_id = character(),
game_date = character(),
season = character(),
session = character(),
game_status = character(),
away_team = character(),
home_team = character(),
game_venue = character(),
game_datetime = character(),
EST_time_convert = character(),
EST_date = character(),
stringsAsFactors = FALSE
)
)
}
## Bind games from schedule list
bind_schedule <- foreach(i = 1:length(schedule_list$dates$games), .combine = rbind) %do% {
schedule_current <- data.frame(
game_id = as.character(schedule_list$dates$games[[i]]$gamePk),
game_date = as.Date(schedule_list$dates$games[[i]]$gameDate),
season = schedule_list$dates$games[[i]]$season,
session = schedule_list$dates$games[[i]]$gameType,
game_status = schedule_list$dates$games[[i]]$status$detailedState,
away_team_id = schedule_list$dates$games[[i]]$teams$away$team$id,
home_team_id = schedule_list$dates$games[[i]]$teams$home$team$id,
game_venue = schedule_list$dates$games[[i]]$venue$name,
game_datetime = schedule_list$dates$games[[i]]$gameDate,
stringsAsFactors = FALSE
)
}
## Modify bound schedule data
schedule_current <- bind_schedule %>%
arrange(game_id) %>%
filter(session != "PR") %>% ## filter out preseason games
mutate(
home_team_id = Team_ID$Team[match(home_team_id, Team_ID$ID)],
away_team_id = Team_ID$Team[match(away_team_id, Team_ID$ID)],
EST_time_convert = format(
as.POSIXct(gsub("T", " ", game_datetime) %>% gsub("Z", "", .),
tz = "UTC",
format = "%Y-%m-%d %H:%M:%S"),
tz = "Canada/Eastern"
),
EST_date = as.Date(
ifelse(is.na(EST_time_convert), as.Date(game_datetime) - 1, EST_time_convert),
origin = "1970-01-01"
),
game_date = EST_date
) %>%
arrange(game_id) %>%
rename(home_team = home_team_id,
away_team = away_team_id
) %>%
data.frame()
## Arrange if playoff games
if ("P" %in% unique(schedule_current$session)) {
schedule_current <- arrange(schedule_current, game_date, EST_time_convert)
}
## print schedule
if (print_sched == TRUE) print(head(schedule_current, 20))
## return schedule
return(schedule_current)
}
## Scrape Events (HTM)
sc.scrape_events_HTM <- function(game_id_fun, season_id_fun, attempts = 3) {
url_events_HTM <- NULL
try_count <- attempts
while (!is.character(url_events_HTM) & try_count > 0) {
url_events_HTM <- try(
getURL(
paste0(
"http://www.nhl.com/scores/htmlreports/",
as.character(season_id_fun),
"/PL0",
as.character(substr(game_id_fun, 6, 10)),
".HTM"
)
)
)
try_count <- try_count - 1
}
## Pull out events data
events_body_text <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_events_HTM), ".bborder"))
}
## Scrape Events (API)
sc.scrape_events_API <- function(game_id_fun, attempts = 3) {
url_events_API <- NULL
try_count <- attempts
while (!is.character(url_events_API) & try_count > 0) {
url_events_API <- try(
getURL(
paste0(
"https://statsapi.web.nhl.com/api/v1/game/",
game_id_fun,
"/feed/live?site=en_nhl"
)
)
)
try_count <- try_count - 1
}
## Parse JSON // Error handling
if (is.character(url_events_API)) {
events_list_API <- try(jsonlite::fromJSON(url_events_API), silent = TRUE)
} else {
events_list_API <- list()
}
if (class(events_list_API) == "try-error") {
events_list_API <- jsonlite::fromJSON(
suppressWarnings(
readLines(paste0("https://statsapi.web.nhl.com/api/v1/game/", game_id_fun, "/feed/live?site=en_nhl"))
)
)
}
if (class(events_list_API) != "list") {
events_list_API <- list()
}
return(events_list_API)
}
## Scrape Events (ESPN)
sc.scrape_events_ESPN <- function(game_id_fun, season_id_fun, game_info_data, attempts = 3) {
## Scrape ESPN to locate game IDs for the specified date
url_ESPN_page <- NULL
try_count <- attempts
while(class(url_ESPN_page) != "character" & try_count > 0) {
url_ESPN_page <- try(
getURL(
.opts = curlOptions(
referer = "www.espn.com",
verbose = FALSE,
followLocation = TRUE
),
# url to scrape
paste0(
"http://www.espn.com/nhl/scoreboard?date=",
gsub("-", "", as.character(game_info_data$game_date))
)
)
)
try_count <- try_count - 1
}
# ## Parse games from scraped ESPN day page
# ESPN_game_ids <- as.character(unique(unlist(str_extract_all(url_ESPN_page, "gameId=[0-9]+")))) %>% gsub("gameId=", "", .)
# ESPN_teams <- toupper(gsub("team/_/name/|>|</div>", "", unique(unlist(str_extract_all(url_ESPN_page, "team/_/name/[a-zA-Z]+|>(Coyotes|Thrashers)</div>")))))
## Get game ids *** New ESPN Scoreboard Page
ESPN_game_ids <- as.character(unique(unlist(str_extract_all(url_ESPN_page, "boxscore/_/gameId/[0-9]+")))) %>% gsub("boxscore/_/gameId/", "", .)
## Get team ids
ESPN_container <- rvest::html_text(rvest::html_node(read_html(url_ESPN_page), "#fittPageContainer"))
ESPN_teams <- toupper(unlist(str_extract_all(ESPN_container, "[0-9A-Z]{4}[a-zA-Z\\s]+[(]+")) %>% gsub("123T|123OTT|123SOT", "", .) %>% gsub("[0-9]|[(]", "", .))
## Get partial team names data frame
part_team_names <- full_team_names %>%
group_by(Team, partTeam) %>%
summarise() %>%
data.frame()
## Check if ESPN URL returned game IDs
if (length(ESPN_game_ids) > 0) {
ESPN_games_df <- suppressWarnings(cbind(
ESPN_game_ids,
matrix(unique(ESPN_teams), byrow = TRUE, ncol = 2)
)) %>%
data.frame(stringsAsFactors = FALSE) %>%
select(
game_id = 1,
away_team = V2,
home_team = V3
) %>%
mutate_at(
vars(home_team, away_team),
funs(toupper(.))
) %>%
mutate_at(
vars(home_team, away_team),
funs(part_team_names$Team[match(., part_team_names$partTeam)])
) %>%
## ensure duplicate games are not created
group_by(game_id) %>%
mutate(index = row_number()) %>%
filter(index == 1) %>%
select(-index) %>%
data.frame()
## Update Teams for Thrashers (WPG -> ATL, 20102011 season and earlier)
ESPN_games_df <- ESPN_games_df %>%
mutate_at(
vars(away_team, home_team),
funs(ifelse(. == "WPG" & game_info_data$season <= 20102011, "ATL", .))
)
## Scrape individual game
ESPN_game_id_ <- filter(ESPN_games_df, away_team == game_info_data$away_team, home_team == game_info_data$home_team)$game_id
url_ESPN_game <- NULL
try_count <- 3
while(class(url_ESPN_game) != "character" & try_count > 0) {
url_ESPN_game <- try(
getURL(
.opts = curlOptions(referer = "www.espn.com",
verbose = FALSE,
followLocation = TRUE),
## url to scrape
paste0("http://www.espn.com/nhl/gamecast/data/masterFeed?lang=en&isAll=true&rand=0&gameId=", ESPN_game_id_)
)
)
try_count <- try_count - 1
}
## Parse xml data
xml_ESPN_events <- url_ESPN_game %>%
gsub("\023", "", .) %>% ## prevent xml parse from erroring
read_xml %>%
xml_nodes("Plays") %>%
xml_children() %>%
xml_text() %>%
strsplit("~") %>%
do.call(rbind, .) %>%
data.frame(stringsAsFactors = FALSE)
return(xml_ESPN_events)
} else {
return(return_char <- "ESPN_NULL")
}
}
## Scrape Shifts (HTM)
sc.scrape_shifts <- function(game_id_fun, season_id_fun, attempts = 3) {
url_home_shifts <- NULL
try_count <- attempts
while (!is.character(url_home_shifts) & try_count > 0) {
url_home_shifts <- try(
getURL(
paste0(
"http://www.nhl.com/scores/htmlreports/",
season_id_fun,
"/TH0",
as.character(substr(game_id_fun, 6, 10)),
".HTM"
)
)
)
try_count <- try_count - 1
}
url_away_shifts <- NULL
try_count <- attempts
while (!is.character(url_away_shifts) & try_count > 0) {
url_away_shifts <- try(
getURL(
paste0(
"http://www.nhl.com/scores/htmlreports/",
season_id_fun,
"/TV0",
as.character(substr(game_id_fun, 6, 10)),
".HTM"
)
)
)
try_count <- try_count - 1
}
## Pull out scraped shifts data
home_shifts_titles <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_home_shifts), ".border"))
away_shifts_titles <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_away_shifts), ".border"))
home_shifts_text <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_home_shifts), ".bborder"))
away_shifts_text <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_away_shifts), ".bborder"))
## Return data as list
return_list <- list(home_shifts_titles = home_shifts_titles,
away_shifts_titles = away_shifts_titles,
home_shifts_text = home_shifts_text,
away_shifts_text = away_shifts_text)
}
## Scrape Shifts (API)
sc.scrape_shifts_API <- function(game_id_fun, attempts = 3) {
url_shifts <- NULL
try_count <- attempts
while (!is.character(url_shifts) & try_count > 0) {
url_shifts <- try(
getURL(
paste0(
"http://www.nhl.com/stats/rest/shiftcharts?cayenneExp=gameId=",
game_id_fun
)
)
)
try_count <- try_count - 1
}
if (is.character(url_shifts)) {
shifts_list <- jsonlite::fromJSON(url_shifts)
} else {
shifts_list <- list()
}
return(shifts_list)
}
## Scrape Rosters
sc.scrape_rosters <- function(game_id_fun, season_id_fun, attempts = 3) {
url_rosters <- NULL
try_count <- attempts
while (is.null(url_rosters) & try_count > 0) {
url_rosters <- try(
getURL(
paste0(
"http://www.nhl.com/scores/htmlreports/",
as.character(season_id_fun),
"/RO0",
as.character(substr(game_id_fun, 6, 10)),
".HTM"
)
)
)
try_count <- try_count - 1
}
## Pull out roster data
rosters_text <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_rosters), "td"))
}
## Scrape Event Summary
sc.scrape_event_summary <- function(game_id_fun, season_id_fun, attempts = 3) {
url_event_summary <- NULL
try_count <- attempts
while (is.null(url_event_summary) & try_count > 0) {
url_event_summary <- try(
getURL(
paste0(
"http://www.nhl.com/scores/htmlreports/",
as.character(season_id_fun),
"/ES0",
as.character(substr(game_id_fun, 6, 10)),
".HTM"
)
)
)
try_count <- try_count - 1
}
## Pull out roster data
event_summary_text <- rvest::html_text(rvest::html_nodes(xml2::read_html(url_event_summary), "td"))
}
## ---------------------------- ##
## Create Basic Data Frames ##
## ---------------------------- ##
## Create Game Information data.frame
sc.game_info <- function(game_id_fun, season_id_fun, events_data, roster_data) {
## Find coaches
coach_index <- which(roster_data %in% c("Head Coaches", "Entraîneurs chef / Head Coaches")) + 1
## Find referees (french format / standard format)
if (roster_data[grep("^Referee|^Arbitre/Referee", roster_data) ] %in% c("Referee", "Arbitre/Referee") &
roster_data[grep("^Referee|^Arbitre/Referee", roster_data) + 1] %in% c("Linesman", "JL/Linesman")) {
referee_index <- grep("^Linesman|^JL/Linesman|^Referee:\\s*", roster_data) + 2
## fix one-off formatting issue
if (roster_data[referee_index] == "\r\n") {
referee_index <- referee_index + 4
}
referee_1 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index ]) %>% gsub("\\s", ".", .)))
referee_2 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 1]) %>% gsub("\\s", ".", .)))
linesman_1 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 3]) %>% gsub("\\s", ".", .)))
linesman_2 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 4]) %>% gsub("\\s", ".", .)))
} else {
referee_index <- grep("^Referee:", roster_data)
referee_1 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 2]) %>% gsub("\\s", ".", .)))
referee_2 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 3]) %>% gsub("\\s", ".", .)))
linesman_1 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 6]) %>% gsub("\\s", ".", .)))
linesman_2 <- na_if_null(toupper(gsub("#[0-9]*\\s", "", roster_data[referee_index + 7]) %>% gsub("\\s", ".", .)))
}
## Find venue & attendance (french format / standard format)
if (sum(grep("Les Formations", roster_data)) == 0) {
venue_vec <- first(roster_data[grep("^Attendance\\s*", roster_data)]) %>% gsub(".*at\\s*", "", .)
attendance_vec <- first(roster_data[grep("^Attendance*", roster_data)]) %>% str_extract(., "[0-9]+,[0-9]+") %>% gsub(",", "", .) %>% as.numeric()
} else {
venue_vec <- first(roster_data[grep("^Ass./Att.\\s*", roster_data)]) %>% gsub(".*@\\s*", "", .)
attendance_vec <- first(roster_data[grep("^Ass./Att.\\s*", roster_data)]) %>% str_extract(., "[0-9]+,[0-9]+") %>% gsub(",", "", .) %>% as.numeric()
}
## Create game info data frame
game_info_df <- data.frame(
game_id = game_id_fun,
season = season_id_fun,
game_date = first(roster_data[grep("^[a-zA-Z]*, ", roster_data)]) %>% gsub("^[a-zA-Z]*, ", "", .) %>% as.Date(., format = "%B %d, %Y") %>% as.character(),
# session = ifelse(as.character(substr(game_id_fun, 6, 10)) > 30000, "P", "R"),
session =
case_when(
as.character(substr(game_id_fun, 6, 10)) > 20000 & as.character(substr(game_id_fun, 6, 10)) < 30000 ~ "R",
as.character(substr(game_id_fun, 6, 10)) > 30000 ~ "P",
as.character(substr(game_id_fun, 6, 10)) < 20000 ~ "PS"
),
game_time_start = first(na.omit(str_extract(roster_data, "[sS]tart\\s*[0-9]+:[0-9]+\\s*[A-Z]+"))) %>% gsub("[sS]tart\\s*", "", .),
game_time_end = first(na.omit(str_extract(roster_data, "[eE]nd\\s*[0-9]+:[0-9]+\\s*[A-Z]+"))) %>% gsub("[eE]nd\\s*", "", .),
venue = venue_vec,
attendance = attendance_vec,
home_team = events_data[8] %>% gsub(" On Ice", "", .),
away_team = events_data[7] %>% gsub(" On Ice", "", .),
home_score = na_if_null(roster_data[grep("^HOME\\b", roster_data) + 1] %>% gsub("\r|\n", "", .) %>% as.numeric()),
away_score = na_if_null(roster_data[grep("^VISITOR\\b", roster_data) + 1] %>% gsub("\r|\n", "", .) %>% as.numeric()),
home_coach = na_if_null(toupper(gsub("\\\r|\\\n", "", roster_data[coach_index + 2]) %>% gsub("\\s", ".", .))),
away_coach = na_if_null(toupper(gsub("\\\r|\\\n", "", roster_data[coach_index ]) %>% gsub("\\s", ".", .))),
referee_1 = ifelse(as.character(substr(game_id_fun, 6, 10)) < 30000, referee_1, NA), ## not adding referees for playoff games ...
referee_2 = ifelse(as.character(substr(game_id_fun, 6, 10)) < 30000, referee_2, NA), ## additional refs present
linesman_1 = ifelse(as.character(substr(game_id_fun, 6, 10)) < 30000, linesman_1, NA),
linesman_2 = ifelse(as.character(substr(game_id_fun, 6, 10)) < 30000, linesman_2, NA),
stringsAsFactors = FALSE
) %>%
mutate(
home_team = ifelse(home_team == "PHX", "ARI", home_team),
away_team = ifelse(away_team == "PHX", "ARI", away_team),
## Fix wrong game date in source
game_date = ifelse(game_id == "2007020003", "2007-10-03", game_date),
## Fix missing data issues
game_time_start = ifelse(game_id == "2009020874", "7:38 MST", game_time_start),
game_time_end = ifelse(game_id == "2009020874", "10:02 MST", game_time_end),
venue = ifelse(game_id == "2009020874", "Jobing.com Arena", venue),
attendance = ifelse(game_id == "2009020874", 13421, attendance),
home_score = ifelse(game_id == "2009020874", 6, home_score),
away_score = ifelse(game_id == "2009020874", 1, away_score)
)
}
## Fix Player Names - HTM
sc.update_names_HTM <- function(data, col_name) {
## Handle input column name
hold_name <- as.name(col_name)
data <- data %>%
mutate(player_name = !!hold_name)
## Find and modify incorrect player names
fixed_names_df <- data %>%
mutate(
player_name =
## Global name changes
case_when(
grepl("^ALEXANDER.|^ALEXANDRE.", player_name) ~ gsub("^ALEXANDER.|^ALEXANDRE.", "ALEX.", player_name),
grepl("^CHRISTOPHER.", player_name) ~ gsub("^CHRISTOPHER.", "CHRIS.", player_name),
TRUE ~ player_name
),
player_name =
## Specific name changes
case_when(
player_name == "ANDREI.KASTSITSYN" ~ "ANDREI.KOSTITSYN",
player_name == "AJ.GREER" ~ "A.J..GREER",
player_name == "ANDREW.GREENE" ~ "ANDY.GREENE",
player_name == "ANDREW.WOZNIEWSKI" ~ "ANDY.WOZNIEWSKI",
player_name == "ANTHONY.DEANGELO" ~ "TONY.DEANGELO",
player_name == "BATES (JON).BATTAGLIA" ~ "BATES.BATTAGLIA",
player_name %in% c("BJ.CROMBEEN", "B.J.CROMBEEN", "BRANDON.CROMBEEN") ~ "B.J..CROMBEEN",
player_name == "BRADLEY.MILLS" ~ "BRAD.MILLS",
player_name == "CAMERON.BARKER" ~ "CAM.BARKER",
player_name == "COLIN (JOHN).WHITE" ~ "COLIN.WHITE",
player_name == "CRISTOVAL.NIEVES" ~ "BOO.NIEVES",
player_name == "CHRIS.VANDE VELDE" ~ "CHRIS.VANDEVELDE",
player_name == "DANNY.BRIERE" ~ "DANIEL.BRIERE",
player_name %in% c("DAN.CLEARY", "DANNY.CLEARY") ~ "DANIEL.CLEARY",
player_name == "DANIEL.GIRARDI" ~ "DAN.GIRARDI",
player_name == "DANNY.O'REGAN" ~ "DANIEL.O'REGAN",
player_name == "DANIEL.CARCILLO" ~ "DAN.CARCILLO",
player_name == "DAVID JOHNNY.ODUYA" ~ "JOHNNY.ODUYA",
player_name == "DAVID.BOLLAND" ~ "DAVE.BOLLAND",
player_name == "DENIS JR..GAUTHIER" ~ "DENIS.GAUTHIER",
player_name == "DWAYNE.KING" ~ "DJ.KING",
player_name == "EDWARD.PURCELL" ~ "TEDDY.PURCELL",
player_name == "EMMANUEL.FERNANDEZ" ~ "MANNY.FERNANDEZ",
player_name == "EMMANUEL.LEGACE" ~ "MANNY.LEGACE",
player_name == "EVGENII.DADONOV" ~ "EVGENY.DADONOV",
player_name == "FREDDY.MODIN" ~ "FREDRIK.MODIN",
player_name == "FREDERICK.MEYER IV" ~ "FREDDY.MEYER",
player_name == "HARRISON.ZOLNIERCZYK" ~ "HARRY.ZOLNIERCZYK",
player_name == "ILJA.BRYZGALOV" ~ "ILYA.BRYZGALOV",
player_name == "JACOB.DOWELL" ~ "JAKE.DOWELL",
player_name == "JAMES.HOWARD" ~ "JIMMY.HOWARD",
player_name == "JAMES.VANDERMEER" ~ "JIM.VANDERMEER",
player_name == "JAMES.WYMAN" ~ "JT.WYMAN",
player_name == "JOHN.HILLEN III" ~ "JACK.HILLEN",
player_name == "JOHN.ODUYA" ~ "JOHNNY.ODUYA",
player_name == "JOHN.PEVERLEY" ~ "RICH.PEVERLEY",
player_name == "JONATHAN.SIM" ~ "JON.SIM",
player_name == "JONATHON.KALINSKI" ~ "JON.KALINSKI",
player_name == "JONATHAN.AUDY-MARCHESSAULT" ~ "JONATHAN.MARCHESSAULT",
player_name == "JOSEPH.CRABB" ~ "JOEY.CRABB",
player_name == "JOSEPH.CORVO" ~ "JOE.CORVO",
player_name == "JOSHUA.BAILEY" ~ "JOSH.BAILEY",
player_name == "JOSHUA.HENNESSY" ~ "JOSH.HENNESSY",
player_name == "JOSHUA.MORRISSEY" ~ "JOSH.MORRISSEY",
player_name == "JEAN-FRANCOIS.JACQUES" ~ "J-F.JACQUES",
player_name %in% c("J P.DUMONT", "JEAN-PIERRE.DUMONT") ~ "J-P.DUMONT",
player_name == "JT.COMPHER" ~ "J.T..COMPHER",
player_name == "KRISTOPHER.LETANG" ~ "KRIS.LETANG",
player_name == "KRYSTOFER.BARCH" ~ "KRYS.BARCH",
player_name == "KRYSTOFER.KOLANOS" ~ "KRYS.KOLANOS",
player_name == "MARC.POULIOT" ~ "MARC-ANTOINE.POULIOT",
player_name == "MARTIN.ST LOUIS" ~ "MARTIN.ST. LOUIS",
player_name == "MARTIN.ST PIERRE" ~ "MARTIN.ST. PIERRE",
player_name == "MARTY.HAVLAT" ~ "MARTIN.HAVLAT",
player_name == "MATTHEW.CARLE" ~ "MATT.CARLE",
player_name == "MATHEW.DUMBA" ~ "MATT.DUMBA",
player_name == "MATTHEW.BENNING" ~ "MATT.BENNING",
player_name == "MATTHEW.IRWIN" ~ "MATT.IRWIN",
player_name == "MATTHEW.NIETO" ~ "MATT.NIETO",
player_name == "MATTHEW.STAJAN" ~ "MATT.STAJAN",
player_name == "MAXIM.MAYOROV" ~ "MAKSIM.MAYOROV",
player_name == "MAXIME.TALBOT" ~ "MAX.TALBOT",
player_name == "MAXWELL.REINHART" ~ "MAX.REINHART",
player_name == "MICHAEL.BLUNDEN" ~ "MIKE.BLUNDEN",
player_name == "MICHAËL.BOURNIVAL" ~ "MICHAEL.BOURNIVAL",
player_name == "MICHAEL.CAMMALLERI" ~ "MIKE.CAMMALLERI",
player_name == "MICHAEL.FERLAND" ~ "MICHEAL.FERLAND",
player_name == "MICHAEL.GRIER" ~ "MIKE.GRIER",
player_name == "MICHAEL.KNUBLE" ~ "MIKE.KNUBLE",
player_name == "MICHAEL.KOMISAREK" ~ "MIKE.KOMISAREK",
player_name == "MICHAEL.MATHESON" ~ "MIKE.MATHESON",
player_name == "MICHAEL.MODANO" ~ "MIKE.MODANO",
player_name == "MICHAEL.RUPP" ~ "MIKE.RUPP",
player_name == "MICHAEL.SANTORELLI" ~ "MIKE.SANTORELLI",
player_name == "MICHAEL.SILLINGER" ~ "MIKE.SILLINGER",
player_name == "MITCHELL.MARNER" ~ "MITCH.MARNER",
player_name == "NATHAN.GUENIN" ~ "NATE.GUENIN",
player_name == "NICHOLAS.BOYNTON" ~ "NICK.BOYNTON",
player_name == "NICHOLAS.DRAZENOVIC" ~ "NICK.DRAZENOVIC",
player_name == "NICKLAS.BERGFORS" ~ "NICLAS.BERGFORS",
player_name == "NICKLAS.GROSSMAN" ~ "NICKLAS.GROSSMANN",
player_name == "NICOLAS.PETAN" ~ "NIC.PETAN",
player_name == "NIKLAS.KRONVALL" ~ "NIKLAS.KRONWALL",
player_name == "NIKOLAI.ANTROPOV" ~ "NIK.ANTROPOV",
player_name == "NIKOLAI.KULEMIN" ~ "NIKOLAY.KULEMIN",
player_name == "NIKOLAI.ZHERDEV" ~ "NIKOLAY.ZHERDEV",
player_name == "OLIVIER.MAGNAN-GRENIER" ~ "OLIVIER.MAGNAN",
player_name == "PAT.MAROON" ~ "PATRICK.MAROON",
player_name %in% c("P. J..AXELSSON", "PER JOHAN.AXELSSON") ~ "P.J..AXELSSON",
player_name %in% c("PK.SUBBAN", "P.K.SUBBAN") ~ "P.K..SUBBAN",
player_name %in% c("PIERRE.PARENTEAU", "PIERRE-ALEX.PARENTEAU", "PIERRE-ALEXANDRE.PARENTEAU", "PA.PARENTEAU", "P.A.PARENTEAU", "P-A.PARENTEAU") ~ "P.A..PARENTEAU",
player_name == "PHILIP.VARONE" ~ "PHIL.VARONE",
player_name == "QUINTIN.HUGHES" ~ "QUINN.HUGHES",
player_name == "RAYMOND.MACIAS" ~ "RAY.MACIAS",
player_name == "RJ.UMBERGER" ~ "R.J..UMBERGER",
player_name == "ROBERT.BLAKE" ~ "ROB.BLAKE",
player_name == "ROBERT.EARL" ~ "ROBBIE.EARL",
player_name == "ROBERT.HOLIK" ~ "BOBBY.HOLIK",
player_name == "ROBERT.SCUDERI" ~ "ROB.SCUDERI",
player_name == "RODNEY.PELLEY" ~ "ROD.PELLEY",
player_name == "SIARHEI.KASTSITSYN" ~ "SERGEI.KOSTITSYN",
player_name == "SIMEON.VARLAMOV" ~ "SEMYON.VARLAMOV",
player_name == "STAFFAN.KRONVALL" ~ "STAFFAN.KRONWALL",
player_name == "STEVEN.REINPRECHT" ~ "STEVE.REINPRECHT",
player_name == "TJ.GALIARDI" ~ "T.J..GALIARDI",
player_name == "TJ.HENSICK" ~ "T.J..HENSICK",
player_name %in% c("TJ.OSHIE", "T.J.OSHIE") ~ "T.J..OSHIE",
player_name == "TOBY.ENSTROM" ~ "TOBIAS.ENSTROM",
player_name == "TOMMY.SESTITO" ~ "TOM.SESTITO",
player_name == "VACLAV.PROSPAL" ~ "VINNY.PROSPAL",
player_name == "VINCENT.HINOSTROZA" ~ "VINNIE.HINOSTROZA",
player_name == "WILLIAM.THOMAS" ~ "BILL.THOMAS",
player_name == "ZACHARY.ASTON-REESE" ~ "ZACH.ASTON-REESE",
player_name == "ZACHARY.SANFORD" ~ "ZACH.SANFORD",
player_name == "ZACHERY.STORTINI" ~ "ZACK.STORTINI",
## NEW CHANGES
player_name == "MATTHEW.MURRAY" ~ "MATT.MURRAY",
player_name == "J-SEBASTIEN.AUBIN" ~ "JEAN-SEBASTIEN.AUBIN",
player_name %in% c("J.F..BERUBE", "JEAN-FRANCOIS.BERUBE") ~ "J-F.BERUBE",
player_name == "JEFF.DROUIN-DESLAURIERS" ~ "JEFF.DESLAURIERS",
player_name == "NICHOLAS.BAPTISTE" ~ "NICK.BAPTISTE",
player_name == "OLAF.KOLZIG" ~ "OLIE.KOLZIG",
player_name == "STEPHEN.VALIQUETTE" ~ "STEVE.VALIQUETTE",
player_name == "THOMAS.MCCOLLUM" ~ "TOM.MCCOLLUM",
player_name == "TIMOTHY JR..THOMAS" ~ "TIM.THOMAS",
TRUE ~ player_name
)
) %>%
data.frame()
## Replace original column with newly created column
fixed_names_df[[col_name]] <- fixed_names_df$player_name
## Return data
return(
fixed_names_df %>%
select(-player_name)
)
}
## Create Rosters data.frame
sc.roster_info <- function(game_id_fun, season_id_fun, roster_data, game_info_data, shifts_list) {
## Get counts of roster & scratched players
roster_player_counts <- lapply(str_extract_all(roster_data[grep("^\r\n#\r\nPos\r\nName|^\r\n#\r\nPos\r\nNom/Name", roster_data)], "[0-9]+"), length)
if (length(roster_player_counts) == 0) { ## extract string for alternate formatting
roster_player_counts <- lapply(str_extract_all(roster_data[grep("^\n#\nPos\nName", roster_data)], "[0-9]+"), length)
}
## Find players in rosters html text
roster_index <- which(roster_data %in% c("Name", "Nom/Name")) + 1
roster_players <- bind_rows(
## Away players
bind_cols(
player = roster_data[seq(roster_index[1] + 2, roster_index[1] + ((roster_player_counts[[1]] - 1) * 3) + 2, by = 3)][1:(roster_player_counts[[1]])],
number = roster_data[seq(roster_index[1] , roster_index[1] + ((roster_player_counts[[1]] - 1) * 3) , by = 3)][1:(roster_player_counts[[1]])],
position = roster_data[seq(roster_index[1] + 1, roster_index[1] + ((roster_player_counts[[1]] - 1) * 3) + 1, by = 3)][1:(roster_player_counts[[1]])]
) %>%
mutate(Team = game_info_data$away_team),
## Home players
bind_cols(
player = roster_data[seq(roster_index[2] + 2, roster_index[2] + ((roster_player_counts[[2]] - 1) * 3) + 2, by = 3)][1:(roster_player_counts[[2]])],
number = roster_data[seq(roster_index[2] , roster_index[2] + ((roster_player_counts[[2]] - 1) * 3) , by = 3)][1:(roster_player_counts[[2]])],
position = roster_data[seq(roster_index[2] + 1, roster_index[2] + ((roster_player_counts[[2]] - 1) * 3) + 1, by = 3)][1:(roster_player_counts[[2]])]
) %>%
mutate(Team = game_info_data$home_team)
) %>%
data.frame(stringsAsFactors = FALSE) %>%
mutate(
player = gsub("\\s*\\([A-Z]\\)", "", player),
player_team_num = paste0(Team, number)
)
## Find scratches
away_scratch_count <- try(roster_player_counts[[3]], silent = TRUE) ## verify both teams provided scratches
home_scratch_count <- try(roster_player_counts[[4]], silent = TRUE) ## verify both teams provided scratches
if (class(away_scratch_count) != "try-error" & class(home_scratch_count) != "try-error") {
roster_scratches <- bind_rows(
## Away scratches
bind_cols(
player = roster_data[seq(roster_index[3] + 2, roster_index[3] + ((away_scratch_count - 1) * 3) + 2, by = 3)][1:away_scratch_count],
number = roster_data[seq(roster_index[3] , roster_index[3] + ((away_scratch_count - 1) * 3) , by = 3)][1:away_scratch_count],
position = roster_data[seq(roster_index[3] + 1, roster_index[3] + ((away_scratch_count - 1) * 3) + 1, by = 3)][1:away_scratch_count]
) %>%
mutate(Team = game_info_data$away_team,
venue = "Away"),
## Home scratches
bind_cols(
player = roster_data[seq(roster_index[4] + 2, roster_index[4] + ((home_scratch_count - 1) * 3) + 2, by = 3)][1:home_scratch_count],
number = roster_data[seq(roster_index[4] , roster_index[4] + ((home_scratch_count - 1) * 3) , by = 3)][1:home_scratch_count],
position = roster_data[seq(roster_index[4] + 1, roster_index[4] + ((home_scratch_count - 1) * 3) + 1, by = 3)][1:home_scratch_count]
) %>%
mutate(Team = game_info_data$home_team,
venue = "Home")
) %>%
data.frame(stringsAsFactors = FALSE) %>%
mutate(
player = gsub("\\s*\\([A-Z]\\)", "", player),
player = gsub("\\s", ".", player),
player_num = as.numeric(number),
player_team_num = paste0(Team, player_num),
position_type = ifelse(position == "G", "G",
ifelse(position == "D", "D",
"F")),
game_id = game_info_data$game_id,
game_date = game_info_data$game_date,
season = game_info_data$season,
session = game_info_data$session,