-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.Rmd
2689 lines (2115 loc) · 101 KB
/
index.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: "Which among the busiest air routes in Europe could actually be travelled by land?"
description: |
Even just considering only air routes with more than 500 000 passengers per year, 75 million passengers a year could get to their destination in less than six hours by train
author:
- name: Giorgio Comai
url: https://giorgiocomai.eu
affiliation: OBCT/EDJNet
affiliation_url: https://www.europeandatajournalism.eu/
date: "`r Sys.Date()`"
creative_commons: CC BY
base_url: https://edjnet.github.io/european_routes
repository_url: https://github.com/EDJNet/european_routes
preview: maps/routes_map_top_gg.png
twitter:
site: "@EdjNet"
creator: "@giocomai"
output:
distill::distill_article:
toc: true
toc_depth: 2
self_contained: true
includes:
in_header: header.html
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, layout = "l-screen")
library("dplyr", warn.conflicts = FALSE) # data wrangling
library("tidyr", warn.conflicts = FALSE) # data wrangling
library("readr", warn.conflicts = FALSE) # read and write csv files
library("ggplot2") # graphs
library("ggiraph") # add some interactivity to graphs
library("reactable") # nice tables in output
library("crosstalk") # some data exploration and interactive filtering of tables
library("leaflet") # interactive maps
library("htmlwidgets") # store and embed interactive maps
library("sf") # geo objects
library("testthat") # some quality checks through the process
library("fs") # consistent file management
```
## Introduction
This document outlines the process of getting data about flights in Europe and matching them with a [dataset recently produced by OBC Transeuropa for Greenpeace](https://www.balcanicaucaso.org/eng/Occasional-papers/Train-alternatives-to-short-haul-flights-in-Europe) that includes details about train travel on the busiest of those routes.
The process seems straightforward, given that Eurostat distributes a number of datasets with flight data, but as will be apparent, there are a number of intermediate steps needed to clean and standardise the data.
These include:
- deal with inconsistencies in the original datasets (missing data, non-standard codes, flights to "unknown airports", to oil rigs, etc.)
- deal with the fact that in some instances more than one airport serve the same city, and within the scope of this analysis all airports serving a given city should really be the same route
- merge data so that routes in both directions are counted as the same
- define which routes cannot possibly be travelled by train (as source or destination are on an island, or exceedingly distant)
- find coordinates of airports and their relative city hubs for visualisation and getting data about distance
- match the result with the above-mentioned train datasets
In the process, a considerable number of intermediate datasets have been generated. You can find some details about them, including a download link, in the [final section of this document](#summary).
## Starting question and operationalisation
**What are the main routes in Europe that are currently travelled by flight but could instead be travelled by train?**
1. We need a dataset with the number of passengers across all main flight routes in Europe
2. We merge routes serving different airports associated to the same city, as the alternative train route would supposedly be more or less the same; if we have to choose a starting point for a land route for people travelling from Luton airport in the UK, we take London, not Luton.
3. We exclude routes with no land/plausible train connection between them, e.g. flights to and from islands that have no train connection. As a result, for example, flights to and from the UK and the European mainland are included (there is a train connection), while all flights from Ireland to the European mainland are excluded. To clarify: flights within Ireland (e.g. Dublin to Cork) would be included by this rule (in practice, no route within islands unconnected to the European mainland is a major European route).
4. We exclude those routes that cannot be reasonably travelled by land or that would take huge amounts of time, and focus only on the main routes for clarity of analysis. To limit the scope of analysis, the train dataset produced by OBC Transeuropa for Greenpeace takes [Eurocontrol's definition of "short haul" flight](https://en.wikipedia.org/wiki/Flight_length#Europe), i.e. all those flights shorter than 1500 km, and keeps only the corresponding routes. In this document, no hard limit is set, but the distance for each route is included in the exported datasets.
Key data sources used in the process are the `avia_par_` datasets distributed by Eurostat and Wikidata (accessed via the [`tidywikidatar` package created for EDJNet](https://edjnet.github.io/tidywikidatar/)).
## The `avia_par_` datasets
Eurostat distributes a series of datasets with details of the number of passengers flying to and from European airports. There is not a unified European dataset, but rather one per country. "avia_par_" (followed by a country code).
Here are some basic information about data availability:
```{r avia_par_search}
fs::dir_create("data")
avia_par_search_file <- fs::path("data", "avia_par_search.csv")
if (fs::file_exists(avia_par_search_file)) {
avia_par_search_df <- readr::read_csv(file = avia_par_search_file, show_col_types = FALSE)
} else {
avia_par_search_df <- eurostat::search_eurostat("Air passenger transport between the main airports of")
readr::write_csv(x = avia_par_search_df, file = avia_par_search_file)
}
avia_par_search_df %>%
dplyr::mutate(title = stringr::str_remove(title, "Air passenger transport between the main airports of ") %>%
stringr::str_remove("and their main partner airports \\(routes data\\)")) %>%
reactable::reactable(filterable = TRUE, sortable = TRUE, resizable = TRUE)
```
To process the data further it is necessary to combine the datasets and make some choices about which data to keep.
In further steps we will:
- keep only data for 2019 (last pre-pandemic year)
- keep only yearly data (more granular data are available for at least some countries)
- keep only data involving European airports included in the datasets (this means, e.g. removing oversea flights such as those to New York)
- use passengers ("PAS") as the unit of analysis (not "seats", or "flights", which would also be available)
- use "passengers carried (departures)"; only departures rather than totals (departure plus arrivals) to prevent double counting, and "passengers carried" (rather than the slightly different "passengers on board").
Having data about `r avia_par_search_df %>% nrow()` European countries, this approach means we should complete data about all flights departing from these these countries.
```{r retrieving avia_par_PAS_CRD_DEP}
avia_par_PAS_CRD_DEP_file <- fs::path("data", "avia_par_PAS_CRD_DEP_df.csv")
if (fs::file_exists(avia_par_PAS_CRD_DEP_file)) {
avia_par_PAS_CRD_DEP_df <- readr::read_csv(file = avia_par_PAS_CRD_DEP_file)
} else {
avia_par_PAS_CRD_DEP_df <- purrr::map_dfr(
.x = avia_par_search_df$code,
.f = function(current_code) {
eurostat::get_eurostat(
id = current_code,
time_format = "num", # year as numeric
select_time = "Y", # yearly data (quarterly and monthly may be available)
filters = list(
time = 2019 # only 2019
)
) %>%
dplyr::mutate(source = current_code) %>%
dplyr::filter(
is.na(values) == FALSE, # drop row when data not available
unit == "PAS", # passengers as unit (not seats or flights
tra_meas == "PAS_CRD_DEP" # passengers carried departures (to prevent double counting)
)
}
)
readr::write_csv(
x = avia_par_PAS_CRD_DEP_df,
file = avia_par_PAS_CRD_DEP_file
)
}
if (fs::file_exists(path = fs::path("data", "airp_pr_codes.csv"))) {
airp_pr_codes_df <- readr::read_csv(file = fs::path("data", "airp_pr_codes.csv"))
} else {
airp_pr_codes_df <- eurostat::get_eurostat_dic(dictname = "airp_pr")
readr::write_csv(x = airp_pr_codes_df, file = fs::path("data", "airp_pr_codes.csv"))
}
```
Here and elsewhere, this document includes some automatic checks to ensure no obvious issues emerge during data processing.
```{r check_double_counting}
library("testthat")
testthat::test_that(
desc = "Only one unit/indicator/timeframe is kept, no double counting",
code = {
expect_equal(
object = avia_par_PAS_CRD_DEP_df %>%
dplyr::distinct(unit) %>%
nrow(),
expected = 1
)
expect_equal(
object = avia_par_PAS_CRD_DEP_df %>%
dplyr::distinct(tra_meas) %>%
nrow(),
expected = 1
)
expect_equal(
object = avia_par_PAS_CRD_DEP_df %>%
dplyr::distinct(time) %>%
nrow(),
expected = 1
)
}
)
```
```{r retrieving avia_par_PAS_CRD_ARR}
# retrieving arrivals for further checks, even if focusing on departures
avia_par_PAS_CRD_ARR_file <- fs::path("data", "avia_par_PAS_CRD_ARR_df.csv")
if (fs::file_exists(avia_par_PAS_CRD_ARR_file)) {
avia_par_PAS_CRD_ARR_df <- readr::read_csv(file = avia_par_PAS_CRD_ARR_file)
} else {
avia_par_PAS_CRD_ARR_df <- purrr::map_dfr(
.x = avia_par_search_df$code,
.f = function(current_code) {
eurostat::get_eurostat(
id = current_code,
time_format = "num", # year as numeric
select_time = "Y", # yearly data (quarterly and monthly may be available)
filters = list(
time = 2019 # only 2019
)
) %>%
dplyr::mutate(source = current_code) %>%
dplyr::filter(
is.na(values) == FALSE, # drop row when data not available
unit == "PAS", # passengers as unit (not seats or flights
tra_meas == "PAS_CRD_ARR" # passengers carried arrivals (to prevent double counting)
)
}
)
readr::write_csv(
x = avia_par_PAS_CRD_ARR_df,
file = avia_par_PAS_CRD_ARR_file
)
}
```
The Eurostat dataset looks as follows, showing data for all flights departing from an airport included in this dataset. It is important to highlight that at this stage this is a rather strange datasets, as it includes flights both from and to European destinations (e.g. taking data on London to Amsterdam from the UK dataset, and Amsterdam to London in the UK dataset), but only departures from flights to non-European destinations (e.g. flights London to New York are included, but New York to London aren't). Routes are defined by a string composed of: `departure_country_code`\_`departure_ICAO_airport_code`\_`arrival_country_code`\_`arrival_ICAO_airport_code`
```{r avia_par_PAS_CRD_DEP table}
avia_par_PAS_CRD_DEP_df %>%
reactable::reactable(filterable = TRUE, sortable = TRUE, resizable = TRUE)
```
.csv file: [`avia_par_PAS_CRD_DEP_df.csv`](data/avia_par_PAS_CRD_DEP_df.csv)
Let's have a look at some summary statistics.
How many routes and passengers appear in the dataset for each country?
```{r layout="l-page"}
avia_par_PAS_CRD_DEP_df %>%
dplyr::group_by(source, .drop = TRUE) %>%
dplyr::summarise(
routes_per_country = dplyr::n(),
total_passengers = sum(values)
) %>%
reactable::reactable(filterable = TRUE, sortable = TRUE, resizable = TRUE,
columns = list(total_passengers = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
))))
```
```{r routes_passengers_scatter_gg, layout="l-body"}
routes_passengers_scatter_gg <- avia_par_PAS_CRD_DEP_df %>%
dplyr::group_by(source, .drop = TRUE) %>%
dplyr::summarise(
routes_per_country = dplyr::n(),
total_passengers = sum(values)
) %>%
dplyr::mutate(country = stringr::str_extract(source, "[a-z][a-z]$") %>% stringr::str_to_upper()) %>%
ggplot2::ggplot(mapping = ggplot2::aes(x = total_passengers, y = routes_per_country)) +
ggplot2::geom_point() +
ggplot2::scale_y_continuous(name = "Number of routes") +
ggplot2::scale_x_continuous(name = "Number of departing passengers", labels = scales::number) +
theme_minimal()
ggiraph::girafe(code = print(routes_passengers_scatter_gg +
ggiraph::geom_point_interactive(aes(tooltip = country), size = 2)))
```
N.B. see which country is which by hovering the graph
At first glance there is no major outlier or piece of data that is self-evidently wrong, but we notice that there are data only from 34 countries, even if the original dataset is available for 35: Turkey is missing.
```{r layout="l-body"}
european_countries_df <- avia_par_PAS_CRD_DEP_df %>%
dplyr::distinct(source) %>%
dplyr::transmute(country_code = stringr::str_extract(source, "[a-z][a-z]$") %>% stringr::str_to_upper())
european_countries_df %>%
reactable::reactable(sortable = TRUE)
```
As it turns out, this is due to the fact that the dataset for Turkey, [avia_par_tr](https://ec.europa.eu/eurostat/databrowser/view/avia_par_tr/default/table?lang=en), does not include data for "passengers on board" (PAS_BRD) but not for "passengers carried" (PAS_CRD).
Plotting the `r nrow(european_countries_df)` countries currently included on a map, we notice that Bosnia and Albania are not included. Pristina airport is inconsistently found among destinations but never as departure. ^[Kosovo is usually marked separately in other maps distributed by the EU, including those with NUTS regions, but not in its world map: https://gisco-services.ec.europa.eu/distribution/v2/countries/download/]. Ercan airport in Northern Cyprus is similarly not included.
```{r layout="l-body"}
world_sf_file <- fs::path("data", "world_geo_data", "world_sf.rds")
if (fs::file_exists(world_sf_file)) {
world_sf <- readr::read_rds(world_sf_file)
} else {
fs::dir_create(fs::path("data", "world_geo_data"))
download.file(
url = "https://gisco-services.ec.europa.eu/distribution/v2/countries/download/ref-countries-2020-60m.geojson.zip",
destfile = fs::path("data", "world_geo_data", "world.geojson.zip")
)
unzip(fs::path("data", "world_geo_data", "world.geojson.zip"),
exdir = fs::path("data", "world_geo_data")
)
world_sf <- sf::st_read(dsn = fs::path("data", "world_geo_data", "CNTR_RG_60M_2020_4326.geojson"))
saveRDS(object = world_sf, file = fs::path("data", "world_geo_data", "world_sf.rds"))
}
ggplot2::ggplot() +
ggplot2::geom_sf(data = world_sf, fill = "lightgrey") +
ggplot2::geom_sf(
data = dplyr::left_join(
x = european_countries_df,
y = world_sf %>% dplyr::rename(country_code = CNTR_ID),
by = "country_code"
) %>%
sf::st_as_sf(),
fill = "lightgreen"
) +
ggplot2::scale_x_continuous(limits = c(-30, 50)) +
ggplot2::scale_y_continuous(limits = c(35, 72)) +
ggplot2::theme_minimal()
```
If we dismiss domestic flights, in principle we could still obtain the relevant data for flights involving European airports included in the dataset, by, for example, adding separately all flights to Bosnia recorded as departures, and all flights from Bosnia recorded in arrivals. We could also include Turkey, based on the rather similar "passengers on board indicator".
```{r avia_par_tr_PAS_BRD_DEP_df}
avia_par_tr_PAS_BRD_DEP_file <- fs::path("data", "avia_par_tr_PAS_BRD_DEP.csv")
if (fs::file_exists(avia_par_tr_PAS_BRD_DEP_file)==FALSE) {
avia_par_tr_PAS_BRD_DEP_df <- eurostat::get_eurostat(
id = "avia_par_tr",
time_format = "num", # year as numeric
select_time = "Y", # yearly data (quarterly and monthly may be available)
filters = list(
time = 2019 # only 2019
)
) %>%
dplyr::mutate(source = "avia_par_tr") %>%
dplyr::filter(
is.na(values) == FALSE, # drop row when data not available
unit == "PAS", # passengers as unit (not seats or flights
tra_meas == "PAS_BRD_DEP" # passengers carried departures (to prevent double counting)
)
} else {
avia_par_tr_PAS_BRD_DEP_df <- readr::read_csv(avia_par_tr_PAS_BRD_DEP_file)
}
```
### Add missing countries and deal with inconsistent data from Czechia
Conceptually, we expect all routes to be travelled in both directions. This is probably the case, but is not fully reflected in the dataset. In particular, data on departure from Czechia include only the country of destination, not the specific airport.
```{r}
avia_par_PAS_CRD_DEP_df %>%
filter(source == "avia_par_cz") %>%
rename(route_code = airp_pr) %>%
left_join(y = airp_pr_codes_df %>% rename(route_code = code_name), by = "route_code") %>%
reactable::reactable()
```
Not all is lost: we can still get all flights from Czechia by taking the dataset on arrivals for all other European countries, which should give the figure we need.
We first remove from the dataset based on departures all routes involving Czechia, then take from the dataset on arrivals all routes as recorded coming from Czechia and merge them.
Since we're at it, let's add also countries that are not (yet) included in the dataset, such as Bosnia, Albania, Kosovo, and Moldova.
```{r avia_par_PAS_CRD_fixed_df}
missing_countries_v <- c("CZ", "BA", "AL", "MD", "XK")
departures_without_cz_df <- avia_par_PAS_CRD_DEP_df %>%
filter(source != "avia_par_cz")
arrivals_with_missing_df <- avia_par_PAS_CRD_ARR_df %>%
mutate(destination_country = stringr::str_extract(
string = airp_pr,
pattern = "[A-Z]{2}(?=_[[:print:]]{4}$)"
)) %>%
filter(destination_country %in% missing_countries_v) %>%
select(-destination_country)
avia_par_PAS_CRD_fixed_df <- bind_rows(
departures_without_cz_df,
arrivals_with_missing_df,
avia_par_tr_PAS_BRD_DEP_df
) %>%
group_by(unit, airp_pr, time, source) %>%
summarise(
tra_meas = "PAS_CRD_DEP",
values = sum(values), .groups = "drop"
) %>%
ungroup() %>%
select(unit, tra_meas, airp_pr, time, values, source)
if (fs::file_exists(fs::path("data", "avia_par_PAS_CRD_fixed.csv")) == FALSE) {
readr::write_csv(
x = avia_par_PAS_CRD_fixed_df,
file = fs::path("data", "avia_par_PAS_CRD_fixed.csv")
)
}
avia_par_PAS_CRD_fixed_df %>%
reactable(filterable = TRUE, sortable = TRUE)
```
.csv file: [avia_par_PAS_CRD_fixed.csv](`data/avia_par_PAS_CRD_fixed.csv`)
So we should have now data about flights to and from these countries. For the countries in yellow there are some more inconsistencies: in particular, only flights to European airports are effectively included and flights among them would not appear.
```{r map of countries included with fixed, layout="l-body"}
ggplot2::ggplot() +
ggplot2::geom_sf(data = world_sf, fill = "lightgrey") +
ggplot2::geom_sf(
data = dplyr::left_join(
x = european_countries_df,
y = world_sf %>% dplyr::rename(country_code = CNTR_ID),
by = "country_code"
) %>%
sf::st_as_sf(),
fill = "lightgreen"
) +
ggplot2::geom_sf(
data = dplyr::left_join(
x = tibble::tibble(country_code = c(missing_countries_v)),
y = world_sf %>% dplyr::rename(country_code = CNTR_ID),
by = "country_code"
) %>%
sf::st_as_sf(),
fill = "gold"
) +
ggplot2::scale_x_continuous(limits = c(-30, 50)) +
ggplot2::scale_y_continuous(limits = c(35, 72)) +
ggplot2::theme_minimal()
```
## Transforming codes into routes
Now that we have a better picture of the scope of the dataset, we can find and use the relevant dictionary to turn airport route codes into more human-readable labels:
```{r airp_pr_code reactable, layout="l-page"}
airp_pr_codes_df %>%
reactable::reactable(filterable = TRUE)
```
.csv file: [`airp_pr_codes.csv`](data/airp_pr_codes.csv)
We also create a more polished version where each airport has its country, code, and name in separate columns.
It appears that occasionally airports located in Serbia, Montenegro, and Kosovo, rather than having the conventional two-letter country code, are marked as "RS_ME", which is a 5 character string. We'll fix them manually.
```{r airp_pr_codes_clean_df}
airp_pr_codes_sep_pre_df <- airp_pr_codes_df %>%
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LYPR", "_XK_LYPR")) %>% # set pristina to XK
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LY99", "_RS_LY99")) %>% # set generic RS_ME to RS
# (anyway, removed in following step, as these are "unknown")
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LYBE", "_RS_LYBE")) %>% # set Belgrade to RS
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LYTI", "_ME_LYTI")) %>% # set Podgorica to ME
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LYPG", "_ME_LYPG")) %>% # set Podgorica to ME
mutate(code_name = stringr::str_replace(code_name, "_RS_ME_LYNI", "_RS_LYNI")) %>% # set Nis to RS
tidyr::separate(
col = code_name,
into = c(
"origin_country",
"origin_airport",
"destination_country",
"destination_airport"
),
sep = "_",
remove = TRUE
) %>%
# filter(origin_country %in% european_countries_df$country_code|destination_country %in% european_countries_df$country_code) %>%
mutate(origin_airport_name = stringr::str_extract(string = full_name, pattern = "^.*(?=airport - )") %>%
stringr::str_remove(" airport.*") %>%
stringr::str_squish()) %>%
mutate(destination_airport_name = stringr::str_extract(string = full_name, pattern = "(?=airport - ).*") %>%
stringr::str_remove_all("airport") %>%
stringr::str_remove(" - ") %>%
stringr::str_squish())
airp_pr_codes_clean_df <- bind_rows(
airp_pr_codes_sep_pre_df %>% transmute(
country = origin_country,
airport_code = origin_airport,
airport_name = origin_airport_name
),
airp_pr_codes_sep_pre_df %>% transmute(
country = destination_country,
airport_code = destination_airport,
airport_name = destination_airport_name
)
) %>%
dplyr::distinct() %>%
# filter(is.na(airport_name)==FALSE,
# stringr::str_detect(airport_code, "99", negate = TRUE),
# stringr::str_detect(airport_code, "00", negate = TRUE),
# airport_name != "Unknown") %>%
distinct(airport_code, .keep_all = TRUE) %>%
dplyr::arrange(country, airport_name)
if (fs::file_exists(fs::path("data", "airp_pr_codes_clean.csv")) == FALSE) {
readr::write_csv(airp_pr_codes_clean_df, file = fs::path("data", "airp_pr_codes_clean.csv"))
}
airp_pr_codes_clean_df %>%
reactable::reactable(filterable = TRUE, sortable = TRUE, resizable = TRUE)
```
.csv file: [`airp_pr_codes_clean.csv`](data/airp_pr_codes_clean.csv)
Merging the two datasets, and putting this in order for the most popular routes, we obtain the following:
```{r routes_dep_label_df}
routes_dep_label_df <- avia_par_PAS_CRD_fixed_df %>%
dplyr::transmute(route_code = airp_pr, pas_crd_dep = values) %>%
dplyr::left_join(
y = airp_pr_codes_df %>% dplyr::rename(route_code = code_name, route_name = full_name),
by = "route_code"
) %>%
dplyr::select(route_code, route_name, pas_crd_dep) %>%
dplyr::arrange(dplyr::desc(pas_crd_dep))
routes_dep_label_df %>%
reactable::reactable(
filterable = TRUE, sortable = TRUE, resizable = TRUE,
columns = list(pas_crd_dep = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
))))
```
```{r include=TRUE}
testthat::test_that(
desc = "Matching of labels leaves no rows unlabelled",
code = {
expect_equal(
object = routes_dep_label_df %>%
dplyr::filter(is.na(route_name)) %>%
nrow(),
expected = 0
)
}
)
```
We notice that some airport codes including double-zero or double-nine (00 or 99) are actually generic codes for "unknown airport in given country".
Beyond Czechia, which other "unknown airports" appear in the dataset?
```{r}
avia_par_PAS_CRD_fixed_labelled_df <- avia_par_PAS_CRD_fixed_df %>%
rename(route_code = airp_pr) %>%
left_join(y = routes_dep_label_df, by = "route_code") %>%
transmute(route_code,
route_name,
passengers = values
)
if (fs::file_exists(fs::path("data", "avia_par_PAS_CRD_fixed_labelled.csv")) == FALSE) {
readr::write_csv(x = avia_par_PAS_CRD_fixed_labelled_df, file = fs::path("data", "avia_par_PAS_CRD_fixed_labelled.csv"))
}
avia_par_PAS_CRD_fixed_labelled_df %>%
reactable::reactable(sortable = TRUE, resizable = TRUE, filterable = TRUE,
columns = list(passengers = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
)))
)
```
.csv file: [`avia_par_PAS_CRD_DEP_labelled.csv`](data/avia_par_PAS_CRD_DEP_labelled.csv)
```{r}
avia_par_PAS_CRD_fixed_labelled_df %>%
dplyr::filter(
stringr::str_detect(string = route_name, pattern = stringr::regex("unknown", ignore_case = TRUE)),
stringr::str_detect(string = route_code, pattern = "^CZ_", negate = TRUE)
) %>%
arrange(desc(passengers)) %>%
reactable::reactable()
```
Somewhat puzzlingly, there are hundreds of thousands of passengers who, according to official data, flew into the unknown taking off from major European airports, mostly from either Brussels or Turkish airports. There is seemingly little we can do to recover those data from the available dataset.
Even besides this, this dataset is however a mess, as it counts travels for both ways for intra-European flights but only one way for extra-European flights. Having only departures, it has for example flights from London to New York, but not from New York to London. However, it has both flights from London to Paris as well as those from Paris to London, the former taken from the `avia_par_uk` dataset, the latter from the `avia_par_fr` dataset.
To get a more meaningful and consistent dataset we should filter the data and keep only routes involving European countries. Besides, we are interested in the total traffic on a route, so that, for example London-Paris and Paris-London passengers are summed together.
First, let's remove all flights involving a non-European airport (to be more precise, an airport that is not located in one of the countries we know are included in the dataset).
So we take it again from the original codes and break out the airport codes:
```{r avia_par_PAS_CRD_fixed_sep_df}
avia_par_PAS_CRD_fixed_sep_df <- avia_par_PAS_CRD_fixed_df %>%
dplyr::select(airp_pr, values) %>%
tidyr::separate(
col = airp_pr,
into = c(
"origin_country",
"origin_airport",
"destination_country",
"destination_airport"
),
sep = "_",
remove = TRUE
) %>%
dplyr::rename(passengers = values)
avia_par_PAS_CRD_fixed_sep_df %>%
reactable::reactable(
filterable = TRUE,
sortable = TRUE,
columns = list(passengers = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
)))
)
```
We can then keep in the "destination_country" column only countries that are present in the "origin_country" column, making sure to keep Czechia.
```{r avia_par_PAS_CRD_fixed_sep_european_df}
avia_par_PAS_CRD_fixed_sep_european_df <- avia_par_PAS_CRD_fixed_sep_df %>%
filter(destination_country %in% unique(c(missing_countries_v, origin_country)))
```
```{r}
# not so relevant after Czechia fix
test_that(desc = "origin countries plus missing countries and destination countries are the same", code = {
expect_equal(
object = avia_par_PAS_CRD_fixed_sep_european_df %>%
distinct(origin_country) %>%
arrange(origin_country) %>%
pull(origin_country) %>%
c(., missing_countries_v) %>%
sort(),
expected = avia_par_PAS_CRD_fixed_sep_european_df %>%
distinct(destination_country) %>%
arrange(destination_country) %>%
pull(destination_country)
)
})
```
We can now add together passengers from both directions of the flight, and have a first ranking of the top European routes included in the dataset. The order of airports within a route is determined by the alphabetical order of the airport code (so, for example, it's Barcelona-Madrid and not vice-versa because Barcelona's airport code - ES_LEBL - alphabetically precedes Madrid's code ES_LEMD). For consistency, this is applied also to the rare cases where only the route in the inverse direction is effectively included in the original dataset. Flights to "unknown airports"are also removed.
There's also a big question about what to do with data from Turkey, which has a lot of busy air routes, many of them domestic. Given that the focus is train routes across the European Union, we'll leave Turkey out of the main analysis, even if some of the busiest domestic routes in Turkey would be clearly good candidates for a train alternative (e.g. the 2.75 million passengers flying between Istanbul and Izmir.)
```{r european_routes_ranking_df}
european_routes_ranking_alf_df <- avia_par_PAS_CRD_fixed_sep_european_df %>%
tidyr::unite(col = "origin_airport", dplyr::contains("origin_"), sep = "_") %>%
tidyr::unite(col = "destination_airport", dplyr::contains("destination_"), sep = "_") %>%
dplyr::mutate(combo_id = row_number()) %>%
tidyr::pivot_longer(
cols = c(
"origin_airport",
"destination_airport"
),
names_to = "type",
values_to = "airport"
) %>%
dplyr::group_by(combo_id) %>%
dplyr::arrange(airport) %>%
dplyr::summarise(
passengers = unique(passengers),
airport = paste(airport, collapse = "_")
) %>%
dplyr::group_by(airport) %>%
dplyr::summarise(passengers = sum(passengers)) %>%
dplyr::transmute(route_code = airport, passengers) %>%
dplyr::arrange(dplyr::desc(passengers)) %>%
dplyr::mutate(ranking = dplyr::row_number()) %>%
left_join(
y = airp_pr_codes_df %>%
dplyr::rename(route_code = code_name, route_name = full_name),
by = "route_code"
) %>%
transmute(ranking, route_code, route_name, passengers) %>%
mutate(
country1 = stringr::str_extract(route_code, pattern = "[A-Z][A-Z]"),
country2 = stringr::str_extract(route_code, pattern = "_[A-Z][A-Z]_") %>% stringr::str_remove_all("_")
) %>%
mutate(type = dplyr::if_else(country1 == country2, "domestic", "international")) %>%
tidyr::unite(col = "country", country1, country2, sep = "_", remove = TRUE)
# dplyr::filter(stringr::str_detect(string = route_name,
# pattern = stringr::regex("Unknown", ignore_case = TRUE), negate = TRUE))
route_names_fix_df <- european_routes_ranking_alf_df %>%
transmute(ranking,
route_code,
route_code_reverse = stringr::str_c(
stringr::str_extract(route_code, "[A-Z]{2}_[[:alnum:]]{4}$"),
"_",
stringr::str_extract(route_code, "^[A-Z]{2}_[[:alnum:]]{4}")
)
) %>%
left_join(
y = airp_pr_codes_df %>%
dplyr::rename(route_code = code_name, route_name = full_name),
by = "route_code"
) %>%
left_join(
y = airp_pr_codes_df %>%
dplyr::rename(
route_code_reverse = code_name,
route_name_reverse = full_name
),
by = "route_code_reverse"
) %>%
transmute(
ranking,
route_name = dplyr::if_else(is.na(route_name),
stringr::str_c(
stringr::str_extract(route_name_reverse, " - [[:print:]]+$") %>%
stringr::str_remove(" - "),
" - ",
stringr::str_extract(route_name_reverse, "^[[:print:]]+ - ") %>%
stringr::str_remove(" - ")
),
route_name
)
)
# which(european_routes_ranking_alf_df$route_name[is.na(european_routes_ranking_alf_df$route_name)])
#
# european_routes_ranking_alf_df$route_name[is.na(european_routes_ranking_alf_df$route_name)] <-
# european_routes_ranking_revalf_df$route_name[is.na(european_routes_ranking_alf_df$route_name)]
european_routes_ranking_with_turkey_df <- european_routes_ranking_alf_df %>%
select(-route_name) %>%
left_join(route_names_fix_df, by = "ranking") %>%
mutate(
origin_airport_code = stringr::str_extract(route_code, "^[A-Z]{2}_[[:alnum:]]{4}"),
destination_airport_code = stringr::str_extract(route_code, "[A-Z]{2}_[[:alnum:]]{4}$"),
origin_airport_name = stringr::str_extract(route_name, "^[[:print:]]+ - ") %>%
stringr::str_remove(" - "),
destination_airport_name = stringr::str_extract(route_name, " - [[:print:]]+$") %>%
stringr::str_remove(" - ")
) %>%
mutate(
origin_airport_country = stringr::str_extract(origin_airport_code, "^[A-Z]{2}"),
destination_airport_country = stringr::str_extract(destination_airport_code, "^[A-Z]{2}"),
origin_airport_icao = stringr::str_remove(origin_airport_code, "^[A-Z]{2}_"),
destination_airport_icao = stringr::str_remove(destination_airport_code, "^[A-Z]{2}_")
) %>%
select(
ranking,
type,
route_code,
passengers,
route_name,
origin_airport_code,
origin_airport_country,
origin_airport_icao,
origin_airport_name,
destination_airport_code,
destination_airport_country,
destination_airport_icao,
destination_airport_name
)
european_routes_ranking_df <- european_routes_ranking_with_turkey_df %>%
filter(origin_airport_country!="TR", destination_airport_country!="TR") %>%
mutate(ranking = row_number())
european_routes_ranking_file <- fs::path(
"data",
"european_routes_ranking.csv"
)
if (fs::file_exists(european_routes_ranking_file) == FALSE) {
readr::write_csv(x = european_routes_ranking_df,
file = european_routes_ranking_file)
readr::write_csv(x = european_routes_ranking_with_turkey_df,
file = fs::path(
"data",
"european_routes_ranking_with_turkey.csv"
))
}
```
Data including Turkey:
```{r}
european_routes_ranking_with_turkey_df %>%
reactable::reactable(
filterable = TRUE,
sortable = TRUE,
columns = list(passengers = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
)))
)
```
.csv file: [`european_routes_ranking_with_turkey.csv`](data/european_routes_ranking_with_turkey.csv)
Data not including Turkey:
```{r}
european_routes_ranking_df %>%
reactable::reactable(
filterable = TRUE,
sortable = TRUE,
resizable = TRUE,
columns = list(passengers = reactable::colDef(format = reactable::colFormat(
separators = TRUE,
digits = 0
)))
)
```
.csv file: [`european_routes_ranking.csv`](data/european_routes_ranking.csv)
Notice that this table includes routes between specific airports, not between cities. We'll get to that in a second.
Before moving on, let's have a quick look at the data we have so far.
```{r european_routes_ranking_scatter_gg, layout="l-body"}
european_routes_ranking_scatter_gg <- european_routes_ranking_df %>%
slice_head(n = 250) %>%
ggplot(mapping = aes(x = type, y = passengers)) +
geom_point() +
scale_y_continuous(
name = "",
labels = scales::number, limits = c(0, NA)
) +
scale_x_discrete("") +
labs(title = "Number of passengers on top 250 European routes") +
theme_minimal()
ggiraph::girafe(code = print(european_routes_ranking_scatter_gg +
ggiraph::geom_point_interactive(aes(tooltip = route_name), size = 2)))
```
Looking at the top routes, we notice that many of the most busy are domestic (hover to see name of the route):
```{r european_routes_ranking_bar_gg, layout="l-body"}
european_routes_ranking_bar_gg <- european_routes_ranking_df %>%
slice_head(n = 20) %>%
arrange(desc(passengers)) %>%
mutate(route_code = forcats::as_factor(route_code)) %>%
ggplot(mapping = aes(x = route_code, y = passengers, fill = type)) +
geom_col() +
scale_y_continuous(
name = "",
labels = scales::number,
limits = c(0, NA)
) +
scale_x_discrete("", labels = rep("", 20)) +
labs(title = "Number of passengers on top 20 European routes") +
theme_minimal() +
theme(legend.title = element_blank(), legend.position = "bottom")
ggiraph::girafe(code = print(european_routes_ranking_bar_gg +
ggiraph::geom_col_interactive(aes(tooltip = route_name))))
```
Time to move on and filter the data further.
### Further oddities in the data
Not yet... :-)
In order to move forward, we must extract the code for each European airport found in the dataset.
```{r layout="l-body"}
origin_airports_df <- avia_par_PAS_CRD_fixed_sep_european_df %>%
transmute(country = origin_country, airport = origin_airport) %>%
distinct(country, airport)
destination_airports_df <- avia_par_PAS_CRD_fixed_sep_european_df %>%
transmute(country = destination_country, airport = destination_airport) %>%
distinct(country, airport)
```
In doing so, it emerges that there are some airports that appear only as the destination, and some only as points of departure, which would be highly unusual and most likely points at some inconsistencies in the data.
Airports found in departures, but not in destinations:
```{r origin_airports_df_reactable, layout="l-body"}
origin_airports_df %>%
anti_join(destination_airports_df, by = "airport") %>%
rename(airport_code = airport) %>%
left_join(y = airp_pr_codes_clean_df %>% select(-country), by = "airport_code") %>%
reactable::reactable(sortable = TRUE, filterable = TRUE)
```
Airports found as destinations, but not as departures (excluding Czechia and the Balkan countries we added separately):
```{r destination_airports_df_reactable, layout="l-body"}
destination_airports_df %>%
filter(!country %in% missing_countries_v) %>%
anti_join(origin_airports_df, by = "airport") %>%
rename(airport_code = airport) %>%
left_join(y = airp_pr_codes_clean_df %>% select(-country), by = "airport_code") %>%
reactable::reactable(sortable = TRUE, filterable = TRUE)
```
Again, short of assuming that the number of flights departing and arriving in an airport is almost always balanced, there is seemingly not much that we can do to fix this. These are anyway all small airport that would anyway not make it to the "top European routes" that is really the objective of this data processing effort.
```{r all_airports_df, layout="l-body"}
all_airports_df <- bind_rows(
origin_airports_df,
destination_airports_df
) %>%
distinct(country, airport) %>%
arrange(country, airport) %>%
filter(stringr::str_detect(string = airport, pattern = "99", negate = TRUE))
```
### Getting the coordinates of airports and the main city they serve
The first step that needs to be made in order to apply further filtering criteria is to to find the coordinates for each of these airports.
There are some on-line datasets with some data about airports, see for example - https://ourairports.com/data/airports.csv - but no apparent official, comprehensive, and free list.
```{r eval = FALSE}
fs::dir_create("data")
airport_codes_file <- fs::path("data", "airports.csv")
if (fs::file_exists(fs::path("data", "airports.csv")) == FALSE) {
download.file(
url = "https://ourairports.com/data/airports.csv",
destfile = airport_codes_file
)
}
airport_codes_df <- readr::read_csv(airport_codes_file)
airport_codes_df$ident[is.na(airport_codes_df$gps_code) == FALSE & airport_codes_df$gps_code == "EPLB"] <- "EPLB" # fix Lublin
airport_codes_df$ident[is.na(airport_codes_df$gps_code) == FALSE & airport_codes_df$gps_code == "LSZM"] <- "LSZM"
```
A useful source for structured data that have no licensing constraints is Wikidata. We can, for example, ask Wikidata for all items that have data for the ICAO code property ("P239"), which is the four-character code that is mostly used to define airports in this dataset. By using Wikidata, we can get coordinates for the vast majority of these airports, as well as gather some additional structured data about them (it is also possible to query for the specific codes included in our dataset, but I prefer to leave this open-ended, facilitating alternative uses).
Wikidata has also a dedicated property - [P931](https://www.wikidata.org/wiki/Property:P931) - to make explicit the fact that an airport is understood to serve a major neighbouring city even if its not located in the relevant municipality (e.g. "London" is the value of property P931 for the Luton airport), which will also be useful later on when we merge multiple airports serving the same cities to gauge total traffic between two hubs. When Wikidata suggests more than one hub, we'll keep only the first.