/
rally-results_review.Rmd
3939 lines (2834 loc) · 139 KB
/
rally-results_review.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: "Visualising WRC Rally Timing and Results Data"
subtitle: "A RallyDataJunkie Adventure"
author: "Tony Hirst"
description: "An introduction to visualising timing and results data for WRC rally events."
knit: "bookdown::render_book"
site: bookdown::bookdown_site
always_allow_html: yes
new_session: no
---
```{r}
options(pillar.sigfig = 7)
```
# Index {-}
<!--chapter:end:index.Rmd-->
---
output:
pdf_document: default
html_document: default
keep_md: true
self_contained: true
---
# Introduction
For fans of WRC, the live timing data screens as well as results from *ewrc-results.com* provide up-to-date information about timing and results over the course of an event weekend, as well as a historical results for the current season (WRC) as well as back into the mists of time (*ewrc-results*).
In this recipe collection, I'll describe various ways of visualising WRC rally results and timing data using data retrieved from the WRC results API. Many of the techniques should also apply directly to data retrieved from other services, such as *ewrc-results.com* if the data is appropriately represented.
<!--chapter:end:intro.Rmd-->
```{r cache = T, echo = F, message=F}
knitr::opts_chunk$set(error = TRUE)
knitr::opts_chunk$set(fig.path = "images/wrc-api-")
```
# Accessing Data from the WRC Live Timing API
We can get rally details, timing and results data from the WRC live timing service JSON API.
## Current Season Rallies
To start with, let's see what rallies are scheduled for the current, active season. The `jsonlite::fromJSON()` will retrieve a JSON (*JavaScript Object Notation*) file from a URL and attempt to unpack it into an *R* dataframe:
```{r message=F, warning=F}
library(jsonlite)
library(stringr)
library(dplyr)
season_url = "https://api.wrc.com/contel-page/83388/calendar/active-season/"
get_active_season = function(active_season_url=season_url, all=FALSE) {
if (all)
jsonlite::fromJSON(active_season_url)
else
jsonlite::fromJSON(active_season_url)$rallyEvents$items
}
s = get_active_season()
# Preview the column names of the resulting dataframe
colnames(s)
```
Let's preview the contents of a couple of those columns:
```{r}
# The tidyr / magrittr pipe syntax makes things easier to read
s %>% select(c('id', 'name')) %>% head()
```
We can search the *name* column to find the unique identifier value for a particular event:
```{r}
eventId = s[s['name']=='Rallye Monte-Carlo','id']
eventId
```
Or we can be more generic with a regular expression lookup:
```{r}
get_eventId_from_name = function(season, name){
season[str_detect(season$name,
regex(name, ignore_case = T)), 'id']
}
get_eventId_from_name(s, 'monte')
```
## Itinerary Lookup
We can make another call to the WRC API to look up the itinerary for the event. Each leg of the event corresponds to a particular day:
```{r}
results_api = 'https://api.wrc.com/results-api'
get_itinerary = function(eventId) {
itinerary = jsonlite::fromJSON(paste0(results_api,"/rally-event/",
eventId,
"/itinerary"))$itineraryLegs
itinerary %>% arrange(order)
}
itinerary = get_itinerary(eventId)
itinerary %>% select(-itinerarySections)
```
The *itinerarySections* columns dataframes describing details of each leg.
### Leg Sections
Within each leg, the itinerary provides information about each section (that is, each "loop") of the rally. This information is retrieved in form of a dataframe in a standard format. We can use the base *R* `do.call()` to call the `rbind()` function against each row of the dataframe and bind all the dataframes in a specified column into a single dataframe:
```{r}
get_sections = function(itinerary){
sections = do.call(rbind, itinerary$itinerarySections)
sections %>% arrange(order)
}
sections = get_sections(itinerary)
sections %>% select(-c(controls, stages))
```
In the sections dataframe we have one row per section. Two of the columns, `*controls* and *stages* each use dataframes to "nest" subdataframes within each row.
For example, here's one of the *controls* dataframes that describes timing controls:
```{r}
sections$controls[[1]]
```
And an example of a dataframe from the first row of the *stages* column:
```{r}
sections$stages[[1]]
```
### Time Controls
We can look up information about each time control from data provided as part of the itinerary lookup using the same trick as before to "unroll" the contents of each dataframe in a specified column into a single dataframe.
An alternative to the `do.call()` approach is to use a tidy approach and use the `dplyr::bind_rows()` function on the `sections$controls` column values via a pipe. We can add a reference to the original section ID by naming each row in the *controls* column with the *itinerarySectionId* value and then ensuring an identifier column is defined when we bind the dataframes:
```{r}
get_controls = function(sections){
# Name each row in the list of dataframes we want to bind
names(sections$controls) = sections$itinerarySectionId
controls = sections$controls %>%
# Ensure that we create an identifier column (uses list names)
bind_rows(.id='itinerarySectionId')
controls
}
controls = get_controls(sections)
controls %>% head(2)
```
### Stage Details
We can pull stage details from the dataframes contained in the `sections` dataframe from the itinerary lookup:
```{r}
get_stages = function(sections){
# Name each row in the list of dataframes we want to bind
names(sections$stages) = sections$itinerarySectionId
stages = sections$stages %>%
# Ensure that we create an identifier column (uses list names)
bind_rows(.id='itinerarySectionId')
stages %>% arrange(number)
}
stages = get_stages(sections)
stages %>% head()
```
We can get a list of stage IDs from the `stageId` column (`stages$stageId`):
```{r}
get_stage_list = function(stages){
stage_list = stages$stageId
stage_list
}
get_stage_list(stages)
```
Perhaps more conveniently, we can create a lookup from code to stage ID:
```{r}
# https://stackoverflow.com/a/19265431/454773
get_stages_lookup = function(stages,
fromCol='code', toCol='stageId'){
stages_lookup = stages[[toCol]]
names(stages_lookup) = stages[[fromCol]]
stages_lookup
}
stages_lookup = get_stages_lookup(stages)
stages_lookup
# Lookup particular stage ID by stage code
#stages_lookup[['SS2']]
```
From the `stages` table, we can get the identifier for a particular stage, either by code (for example, *"SS3"*) or by (partial) name match:
```{r}
ssnum = 'SS3'
get_stage_id = function(stages, sname, typ='code'){
# code, name
if (typ=='code')
stageId = stages[stages[typ] == sname, 'stageId']
else
stageId = stages[stringr::str_detect(stages[[typ]], sname), 'stageId']
stageId
}
stageId = get_stage_id(stages, 'Mustalampi 1', 'name')
stageId
```
And the stage distance and name:
```{r}
get_stage_info = function(stages, sid, typ='stageId', clean=TRUE){
# stageId, code
name=stages[stages[typ] == sid, 'name']
distance=stages[stages[typ] == sid, 'distance']
if (clean)
stringr::str_replace(name, ' (Live TV)', '')
c(name=name, distance=distance)
}
get_stage_info(stages, stageId)
```
### Road Order Start Lists
The *startListId* can be used alongside the event ID to look up the startlist for a leg. We can order the startlist by start order:
```{r}
get_startlist = function(eventId, startListId) {
startlist_url = paste0(results_api, '/rally-event/',
eventId,'/start-list-external/', startListId)
startlist = jsonlite::fromJSON(startlist_url)$startListItems
# Order the startlist dataframe by start order
startlist %>% arrange(order)
}
# Example startlist ID
# Use a regular expression to find the startlist ID by day
startListId = itinerary[str_detect(itinerary$name,
regex('Friday', ignore_case = T)),
'startListId']
startlist = get_startlist(eventId, startListId)
startlist %>% head()
```
Looking up a startlist ID is a little fiddly:
```{r}
get_startlist_id = function(itinerary, itinerarySectionId){
sections = get_sections(itinerary)
itineraryLegId = sections[sections$itinerarySectionId==itinerarySectionId,
'itineraryLegId']
itinerary[itinerary$itineraryLegId==itineraryLegId,'startListId']
}
get_startlist_id(itinerary, stages$itinerarySectionId[[1]])
```
## Competitor Details
Details of car entries for each event can be retrieved from the WRC live timing API given an event ID.
```{r}
get_rally_entries = function(eventId) {
cars_url = paste0(results_api, '/rally-event/',
eventId,'/cars')
jsonlite::fromJSON(cars_url)
}
entries = get_rally_entries(eventId)
# $driver, $codriver, $manufacturer, $entrant, $group, $eventClasses
# $identifier, $vehicleModel, $eligibility, $status
entries %>% head(2)
```
### Looking Up Entries by Group
We can index the entries by group to find all the WRC car `entryId` values:
```{r}
entries[entries$group$name=='WRC', 'entryId']
```
### Driver & Codriver Details
Detailed information for each driver and codriver can be found in the corresponding sub-dataframes.
For example, we can look up the details for each driver, noting in this case that we need to column bind (`cbind()`) the subdataframes to produce the collated dataframe of driver details:
```{r}
get_drivers = function(entries){
drivers = do.call(cbind, entries$driver)
drivers
}
drivers = get_drivers(entries)
drivers %>% head(2)
```
We can similarly obtain data for the codrivers:
```{r}
#codrivers = do.call(cbind, entries$codriver)
# Again, there is a tidyverse approach with dplyr::bind_cols()
get_codrivers = function(entries){
codrivers = bind_cols(entries$codriver)
codrivers
}
codrivers = get_codrivers(entries)
codrivers %>% head(2)
```
We can conveniently obtain the identifier for a particular driver or codriver by searching against their name or three letter code, although note that *the three letter code may not be a unique identifier*:
```{r}
get_person_id = function(persons, sname, typ='fullName'){
# code, fullName
if (typ=='code')
personsId = persons[persons[typ]==sname, 'personId']
else
personId = persons[str_detect(persons[[typ]],
regex(sname,
ignore_case = T)),
'personId']
personId
}
ogierDriverId = get_person_id(drivers, 'ogier')
ogierDriverId
```
From the driver person identifier we can get the entry identifier for the rally we're exploring:
```{r}
ogierEntryId = entries[entries['driverId']==ogierDriverId, 'entryId']
ogierEntryId
```
### Summarising Essential Entry Data
We can manually create a dataframe containing essential fields from the original cars dataframe and the dataframes contained within it:
```{r}
get_car_data = function(entries){
cols = c('entryId', 'driverId', 'codriverId','manufacturerId',
'vehicleModel','eligibility', 'classname','manufacturer',
'entrantname', 'groupname', 'drivername', 'code',
'driverfullname', 'codrivername','codriverfullname'
)
entries = entries %>%
rowwise() %>%
mutate(classname = eventClasses$name) %>%
mutate(manufacturer = manufacturer$name) %>%
mutate(entrantname = entrant$name) %>%
mutate(groupname = group$name) %>%
mutate(drivername = driver$abbvName) %>%
mutate(driverfullname = driver$fullName) %>%
mutate(codrivername = codriver$abbvName) %>%
mutate(codriverfullname = codriver$fullName) %>%
mutate(code = driver$code) %>%
select(all_of(cols))
# If we don't cast, it's a non-rankable rowwise df
as.data.frame(entries)
}
get_car_data(entries) %>% head(2)
```
## Penalties and Retirements
We can look up *penalties* from an event ID:
```{r}
get_penalties = function(eventId) {
penalties_url = paste0(results_api, '/rally-event/',
eventId, '/penalties')
jsonlite::fromJSON(penalties_url)
}
get_penalties(eventId) %>% head(2)
```
The event ID is also all we need to request a list of *retirements*:
```{r}
get_retirements = function(eventId) {
retirements_url = paste0(results_api, '/rally-event/',
eventId, '/retirements')
jsonlite::fromJSON(retirements_url)
}
get_retirements(eventId) %>% head(2)
```
## Results and Stage Winner
As well as retrieving penalties and retirements using just the event ID as a key, we can also retrieve the overall results and the stage winners:
```{r}
get_result = function(eventId) {
result_url = paste0(results_api, '/rally-event/',
eventId,'/result')
jsonlite::fromJSON(result_url)
}
get_result(eventId) %>% head(2)
```
And for the stage winners:
```{r}
get_stage_winners = function(eventId) {
stage_winners_url = paste0(results_api, '/rally-event/',
eventId,'/stage-winners')
jsonlite::fromJSON(stage_winners_url)
}
get_stage_winners(eventId) %>% head(2)
```
## Stage Result
At the end of each stage, there are actually two different sorts of results data are available: data relating to the result of the stage itself, and data relating to how the stage result affected the overall rally position.
Let's start by getting the overall rally result at the end of a particular stage. Note that the overall result does not include the stage ID in the returned data so we need to add it in:
```{r}
get_overall_result = function(eventId, stageId) {
overall_url = paste0(results_api, '/rally-event/',
eventId, '/stage-result/stage-external/',
stageId)
jsonlite::fromJSON(overall_url) %>%
# Also add in the stage ID
mutate(stageId = stageId)
}
overall_result = get_overall_result(eventId, stageId)
overall_result %>% head(2)
```
### Getting Stage Results for Multiple Stages
It will be convenient to be able to retrieve overall results for multiple stages from one function call. One way of achieving that is to create a function to retrieve the details for a single specified stage that can be applied via a `purrr::map()` function call to a list of the stage IDs we want overall results data for:
```{r}
library(purrr)
get_overall_result2 = function(stageId, eventId) {
get_overall_result(eventId, stageId)
}
get_multi_overall = function(stage_list){
multi_overall = stage_list %>%
map(get_overall_result2, eventId=eventId) %>%
bind_rows()
multi_overall
}
# Specify the stage IDs for multiple stages
stage_list = c(1747, 1743)
multi_overall_results = get_multi_overall(stage_list)
multi_overall_results %>% tail(2)
```
## Stage Times
We can get the stage times for each stage on a rally by event and stage ID:
```{r}
get_stage_times = function(eventId, stageId) {
stage_times_url = paste0(results_api, '/rally-event/',
eventId, '/stage-times/stage-external/',
stageId)
jsonlite::fromJSON(stage_times_url)
}
stage_times = get_stage_times(eventId, stageId)
stage_times %>% head(2)
```
### Getting Stage Times for Multiple Stages
It will also be convenient to be able to retrieve stage times for multiple stages from a single function call. We can take the same approach we used previously:
```{r message=F, warning=F}
get_stage_times2 = function(stageId, eventId) {
get_stage_times(eventId, stageId)
}
get_multi_stage_times = function(stage_list){
multi_stage_times = stage_list %>%
map(get_stage_times2, eventId=eventId) %>%
bind_rows()
multi_stage_times
}
multi_stage_times = get_multi_stage_times(stage_list)
multi_stage_times %>% tail(2)
```
### Getting Wide Stage Times for Multiple Stages
We can then widen the stage times for each driver:
```{r}
get_multi_stage_times_wide = function(multi_stage_times, stage_list){
stage_times_cols = c('entryId', 'stageId', 'elapsedDurationMs')
multi_stage_times_wide = multi_stage_times %>%
select(all_of(stage_times_cols)) %>%
mutate(elapsedDurationS = elapsedDurationMs / 1000) %>%
select(-elapsedDurationMs) %>%
group_by(entryId) %>%
tidyr::spread(key = stageId,
value = elapsedDurationS) %>%
select(c('entryId', as.character(stage_list))) %>%
# If we don't cast, it's a
# non-rankable rowwise df
as.data.frame()
multi_stage_times_wide
}
multi_stage_times_wide = get_multi_stage_times_wide(multi_stage_times,
stage_list)
multi_stage_times_wide %>% head(2)
```
### Getting Wide Stage Positions
We can also get the stage positions:
```{r}
get_multi_stage_positions_wide = function(multi_stage_times, stage_list){
stage_positions_cols = c('entryId', 'stageId', 'position')
multi_stage_positions_wide = multi_stage_times %>%
select(all_of(stage_positions_cols)) %>%
group_by(entryId) %>%
tidyr::spread(key = stageId,
value = position) %>%
select(c('entryId', as.character(stage_list))) %>%
# If we don't cast, it's a
# non-rankable rowwise df
as.data.frame()
}
multi_stage_positions_wide = get_multi_stage_positions_wide(multi_stage_times, stage_list)
multi_stage_positions_wide %>% head(2)
```
### Getting Generic Wide Dataframes
We can start to work up a function that is able to handle widening data frames more generally, albeit with a potential need to handle exceptions:
```{r}
get_multi_stage_generic_wide = function(multi_stage_generic, stage_list,
wide_val, group_key='entryId',
spread_key='stageId'){
stage_times_cols = c(group_key, spread_key, wide_val )
if (wide_val=='elapsedDurationMs') {
multi_stage_times_wide = multi_stage_times %>%
select(all_of(stage_times_cols)) %>%
mutate(elapsedDurationS = elapsedDurationMs / 1000) %>%
select(-elapsedDurationMs)
wide_val = 'elapsedDurationS'
}
multi_stage_generic_wide = multi_stage_generic %>%
select(all_of(stage_times_cols)) %>%
# group_by_at lets us pass in the grouping column by variable
group_by_at(group_key) %>%
tidyr::spread(key = spread_key,
value = wide_val) %>%
select( c(group_key, as.character(stage_list))) %>%
# If we don't cast, it's a
# non-rankable rowwise df
as.data.frame()
multi_stage_generic_wide
}
multi_stage_positions_wide_g = get_multi_stage_generic_wide(multi_stage_times, stage_list, 'position')
multi_stage_positions_wide_g %>% head(2)
```
## Split Times
We can get split times and distance into stage data for each stage given the stage identifier:
```{r}
get_splits = function(eventId, stageId){
splits_url=paste0(results_api, '/rally-event/', eventId,
'/split-times/stage-external/', stageId)
jsonlite::fromJSON(splits_url)
}
splits = get_splits(eventId, stageId)
# $splitPoints
# $entrySplitPointTimes
```
This includes handy information about split locations, such as distance into stage. This can also be useful for pace calculations:
```{r}
splits$splitPoints
```
We can also view the split point times for each driver. This second dataframe contains rows summarising the stage for each driver, and includes the stage start time and duration as well as a column *splitPointTimes* that itself contains a data frame of elapsed duration split point times:
```{r}
splits$entrySplitPointTimes %>% select(-splitPointTimes) %>% head(2)
```
To view the split times for a specific driver, we can index into the dataframe using the driver `entryId` value:
```{r}
splits$entrySplitPointTimes[splits$entrySplitPointTimes['entryId']==ogierEntryId,]$splitPointTimes
```
Each dataframe gives the split times on the stage for a particular driver in a long format.
Note that the split point times are strictly increasing and describe the elapsed time into the stage at each split point from the start location and time.
### Driver Split Times Detail
We can get an unrolled long structure by combining the *splitPointTimes* dataframes from all drivers, also taking the opportunity to convert the elapsed duration in milliseconds to seconds along the way:
```{r}
#driver_splits = do.call(rbind, entry_splits$splitPointTimes)
# The tidyverse approach is to use dplyr::bind_rows()
# We can also construct a pipe to streamline the processing
get_driver_splits = function(splits){
driver_splits = splits$entrySplitPointTimes$splitPointTimes %>%
bind_rows() %>%
mutate(elapsedDurationS = elapsedDurationMs / 1000) %>%
select(-elapsedDurationMs)
driver_splits
}
driver_splits = get_driver_splits(splits)
driver_splits %>% head(2)
```
### Wide Driver Split Times
We can cast the data into a wide format, with splits ordered by their distance into the stage. Start by creating a function to help get the split point codes in order by distance along the stage:
```{r}
get_split_cols = function(splits){
split_cols = as.character(arrange(splits$splitPoints, distance)$splitPointId)
split_cols
}
```
Now create a function to get the driver splits in a wide format using the distance-into-stage ordered split point codes as the widened columns:
```{r}
get_driver_splits_wide = function(driver_splits, splits){
split_cols = get_split_cols(splits)
splits_cols = c('entryId', 'splitPointId', 'elapsedDurationS')
driver_splits_wide = driver_splits %>%
group_by(entryId) %>%
select(all_of(splits_cols)) %>%
tidyr::spread(key = splitPointId,
value = elapsedDurationS) %>%
select(all_of(c('entryId', split_cols))) %>%
# If we don't cast, it's a
# non-rankable rowwise df
as.data.frame()
driver_splits_wide
}
driver_splits_wide = get_driver_splits_wide(driver_splits, splits)
driver_splits_wide %>% head(2)
```
### Multiple Stage Long Splits Data
A convenient way of working with the split times across multiple stages is to put the splits into a long form and then filter out the rows we are interested in.
We can generate a long form dataframe using the `dlplyr::bind_rows()` that we have met before:
```{r}
get_split_times2 = function(stageId, eventId) {
splits = get_splits(eventId, stageId)
split_times = splits$entrySplitPointTimes
names(split_times$splitPointTimes) = splits$splitPoints$splitPointId
split_times$splitPointTimes
}
get_multi_split_times = function(stage_list){
multi_split_times = stage_list %>%
map(get_split_times2, eventId=eventId) %>%
bind_rows()
multi_split_times
}
stage_list_sample = stage_list[1:2]
get_multi_split_times(stage_list[1:2]) %>% head(3)
```
<!--chapter:end:wrc-api.Rmd-->
```{r cache = T, echo = F, message=F}
knitr::opts_chunk$set(error = TRUE)
knitr::opts_chunk$set(fig.path = "images/itinerary-")
```
# Itinerary & Road Position
The competitive phase of a full WRC Rally event typically extends over three days (Friday to Sunday), with either a ceremonial start or a short first stage on the Thursday evening. Shorter format events are also possible.
Each day is referred to as a *leg*, and each leg is structured as a *section*, often referred to as a *loop*.
## Load Base Data
Start by loading in the base WRC API helper functions:
```{r message=F, warning=F}
source('code/wrc-api.R')
library(tidyr)
```
And grab some minimal event metadata:
```{r}
s = get_active_season()
eventId = get_eventId_from_name(s, 'arctic')
```
## Displaying the Itinerary
We can grab the full itinerary with a single function call:
```{r}
itinerary = get_itinerary(eventId)
itinerary
```
The *status* often does not get updated at the end of the event, so completed events may still describe the final day as *Running*.
```{r}
itinerary %>% select(c('name', 'legDate'))
```
### Itinerary Legs
Let's have a look at the structure of a particular day:
```{r message=FALSE, warning=FALSE}
example_section = itinerary[[1, 'itinerarySections']]
example_section
```
We can also get the full set of itinerary sections in one dataframe:
```{r}
itinerary_sections_full = do.call(rbind, itinerary$itinerarySections)
itinerary_sections_full
```
### Itinerary Controls
The *controls* column details information about all the timing controls:
```{r}
example_controls = example_section[[1, 'controls']]
example_controls
```
Let's see the key information for the controls:
```{r message=FALSE}
controls_cols = c('controlId', 'eventId', 'type',
'code', 'location', 'distance', 'firstCarDueDateTime')
example_controls %>% select(controls_cols)
```
We can get a list of all the controls by combining data from the separate legs dataframes:
```{r}
get_multi_controls = function(itinerary_sections){
multi_controls = do.call(rbind, itinerary_sections$controls)
multi_controls %>% select(controls_cols)
}
```
Let's see how it works:
```{r}
multi_controls = get_multi_controls(itinerary_sections_full)
multi_controls %>% tail()
```
### Itinerary Stages
The *stages* column provides more information about each stage:
```{r}
example_stages = example_section[[1, 'stages']]
example_stages
```
Let's focus on the key columns:
```{r meddage=FALSE}
stages_cols = c('stageId', 'eventId', 'number', 'name',
'distance', 'stageType', 'code')
stage_name_cleaner = function(df) {
df %>%
mutate(fullname=name,
name=stringr::str_replace(name, ' \\(Live TV\\)', '')) %>%
mutate(fullname=name,
name=stringr::str_replace(name, ' \\(Wolf Power Stage\\)', ''))
}
example_stages %>%
select(stages_cols) %>%
stage_name_cleaner
```
Once again, we can pull all the information into a single dataframe:
```{r}
get_multi_stage_details = function(itinerary){
multi_stage_details = do.call(rbind, itinerary$stages)
multi_stage_details %>%
select(stages_cols) %>%
stage_name_cleaner()
}
```
Here's how it works:
```{r}
multi_stage_details = get_multi_stage_details(itinerary_sections_full)
multi_stage_details %>% tail()
```
<!--chapter:end:itinerary.Rmd-->
```{r cache = T, echo = F, message=F}
knitr::opts_chunk$set(error = TRUE)
knitr::opts_chunk$set(fig.path = "images/stage-results-")
```
# Visualising Results for a Single Stage
In this chapter, we'll introduce some basic chart and chartable techniques for displaying stage timing and results data.
## Load Base Data
To get the splits data from a standing start, we can load in the current season list, select the rally we want, look up the itinerary from the rally, extract the sections and then the stages and the retrieve the stage ID for the stage we are interested in.
To begin with, load in our WRC API helper functions:
```{r message=F, warning=F}
source('code/wrc-api.R')
```
Now let's grab some data:
```{r}
s = get_active_season()
eventId = get_eventId_from_name(s, 'arctic')
entries = get_rally_entries(eventId)
itinerary = get_itinerary(eventId)
sections = get_sections(itinerary)
stages = get_stages(sections)
stages_lookup = get_stages_lookup(stages)
```
Get a sample stage ID:
```{r}
stageId = stages_lookup[['SS3']]
```
## Get Stage Results Data
Start by loading in some stage times data and previewing the columns available to us:
```{r}
stage_times = get_stage_times(eventId, stageId)
colnames(stage_times)
```
## Previewing Stage Results Data
Just using the stage results data, how might we display it?
Let's start with a view of the top 10. We can use the `knitr::kable()` function to provide a styled version of the table that slightly improves its appearance:
```{r}
library(knitr)
kable( head(stage_times, 10))
```
An alternative rich table formatter is the [`formattable`](https://github.com/renkun-ken/formattable) ([example usage](https://www.displayr.com/formattable/)) *R* package which builds on `kable()` and provides even more comprehensive support,, including cell colour highlighting, for rendering tables in a stylised way. In interactive HTML environments, the tables are rendered as an HTML widget, which allows for even more customisation, such as the inclusion of interactive HTML sparklines.
```{r}
library(formattable)
formattable( head(stage_times, 10) )
```
The data itself looks quite cryptic, so we need to convert it to something a little bit more human readable. To enrich the display, we might want to add in information relating to a stage, rather than just refer to it by stage ID, or to describe each entry in rather more detail than just by the entry ID.
The way the table is actually presented may also mean that not all the columns may be displayed, so reducing the number of columns would presumably help address that, in part at least.
### Adding Entry Metadata
In the first instance, it would probably make sense to pull in some human readable data about each entry:
```{r}
cars = get_car_data(entries)
cars %>% head(2)
```
We can the merge this data into our original table, and filter out some of the less useful columns. Since the driver code may not be unique, we should retain the driver `entryId` in the table and then suppress its display when we render the dataframe. We'll also limit ourselves to just the top 10 results.
```{r}
top10_display_cols_base = c('position', 'identifier', 'code',
#'drivername', 'codrivername',
#'groupname', 'entrantname',
#'classname', 'eligibility',
#'elapsedDuration',
# gap is the time delta between a driver
# and the leader; diff (or interval)
# is the difference between a driver
# and the driver immediately ahead
'TimeInS', 'gap', 'diff')
top10_stage_times = stage_times %>%
# A minor optimisation step to
# limit the amount of merging
arrange(position) %>%