Last updated: 2021-09-08
Checks: 7 0
Knit directory: myTidyTuesday/
This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.
Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.
Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.
The command set.seed(20210907)
was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.
Great job! Recording the operating system, R version, and package versions is critical for reproducibility.
Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.
Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.
The results in this page were generated with repository version 804a731. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.
Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish
or wflow_git_commit
). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:
Ignored files:
Ignored: .Rhistory
Ignored: .Rproj.user/
Ignored: catboost_info/
Ignored: data/2021-09-08/
Ignored: data/acs_poverty.rds
Ignored: data/hike_data.rds
Ignored: data/us_states.rds
Unstaged changes:
Modified: code/_common.R
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.
These are the previous versions of the repository in which changes were made to the R Markdown (analysis/TourDeFrance.Rmd
) and HTML (docs/TourDeFrance.html
) files. If you’ve configured a remote Git repository (see ?wflow_git_remote
), click on the hyperlinks in the table below to view the files as they were in that past version.
File | Version | Author | Date | Message |
---|---|---|---|---|
Rmd | 804a731 | opus1993 | 2021-09-08 | fix aspect ratio, theme |
Inspired by the work of Alastair Rushworth at Visualising Tour De France Data In R
and by the R4DS learning community #TidyTuesday
suppressPackageStartupMessages({
library(tidyverse)
library(paletteer)
library(ggtext)
library(rvest)
library(lubridate)
library(patchwork)
})
source(here::here("code","_common.R"),
verbose = FALSE,
local = knitr::knit_global())
Registered S3 method overwritten by 'tune':
method from
required_pkgs.model_spec parsnip
ggplot2::theme_set(theme_jim(base_size = 12))
tuesdata <- tidytuesdayR::tt_load('2020-04-07')
--- Compiling #TidyTuesday Information for 2020-04-07 ----
--- There are 3 files available ---
--- Starting Download ---
Downloading file 1 of 3: `stage_data.csv`
Downloading file 2 of 3: `tdf_stages.csv`
Downloading file 3 of 3: `tdf_winners.csv`
--- Download complete ---
tdf_winners <- tuesdata$tdf_winners %>%
mutate(year = ymd(year(start_date),truncated = 2L),
speed = distance / time_overall)
stage_data <- tuesdata$stage_data
tdf_stages <- tuesdata$tdf_stages %>%
janitor::clean_names() %>%
mutate(year = year(date))
showtext::showtext_auto()
cf_io <- read_html("https://www.countryflags.io/")
country_ids <- cf_io %>%
html_nodes(".item_country") %>%
lapply(function(el) {
key <- el %>%
html_text() %>%
str_split("\\n") %>%
`[[`(1) %>%
trimws() %>%
{
.[nchar(.) > 0]
}
data.frame(
code = key[1],
nationality = key[2]
)
}) %>%
bind_rows()
get_country_flag <- function(x) {
urls <- sapply(x, function(x) {
code <- country_ids$code[which(country_ids$nationality == x)]
file.path("https://www.countryflags.io", code, "flat/64.png")
})
paste0("<img src='", urls, "' width='30' />")
}
Nationalities of the Winners
tdf_nations <- tdf_winners %>%
mutate(
nationality = stringr::str_squish(nationality),
nationality = case_when(
nationality == "Great Britain" ~ "United Kingdom",
TRUE ~ nationality
)
) %>%
count(nationality, sort = TRUE) %>%
mutate(nationality = fct_reorder(nationality, n)) %>%
top_n(8, n)
flag_labels <- get_country_flag(tdf_nations$nationality)
pal <- RColorBrewer::brewer.pal("Set1", n = 8)
nations <- tdf_nations %>%
ggplot(aes(n, nationality)) +
geom_bar(fill = 2, stat = "identity") +
scale_y_discrete(name = NULL, labels = flag_labels) +
scale_fill_discrete(guide = FALSE) +
theme_jim(base_size = 10) +
theme(
axis.text.y = ggtext::element_markdown(color = "black", size = 11),
axis.title.y = element_blank(),
plot.title.position = "plot",
panel.grid.major.y = element_blank()
) +
expand_limits(x = c(0, 45)) +
labs(
title = "National Wins",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
Physical characteristics and race characteristics by decade
by_decade <- tdf_winners %>%
group_by(decade = 10 * (year(year) %/% 10)) %>%
summarize(
winner_age = mean(age, na.rm = TRUE),
winner_height = mean(height, na.rm = TRUE),
winner_weight = mean(weight, na.rm = TRUE),
winner_margin = mean(time_margin, na.rm = TRUE),
winner_time = mean(time_overall, na.rm = TRUE),
winner_speed = mean(speed, na.rm = TRUE)
)
p1 <- by_decade %>%
ggplot(aes(decade, winner_age)) +
geom_line(color = 4, size = 3, show.legend = FALSE) +
expand_limits(y = 0) +
labs(
y = "",
title = "Average Age of Tour de France Winners By Decade",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
p1
p2 <- by_decade %>%
ggplot(aes(decade, winner_margin)) +
geom_line(color = 5, size = 3) +
expand_limits(y = 0) +
labs(
y = "Hours",
title = "Margin of Victory of Tour de France Winners By Decade",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
p2
p3 <- by_decade %>%
ggplot(aes(decade, winner_speed)) +
geom_line(color = 6, size = 3) +
expand_limits(y = 0) +
labs(
y = "Hours",
title = "Average Speed of Tour de France Winners By Decade",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
p3
Life Expectancy of TDF winners with survival analysis
extrapolated for the riders 38 still alive (not yet dead)
library(survival)
surv_model <- tdf_winners %>%
distinct(winner_name, .keep_all = TRUE) %>%
transmute(
birth_year = year(born),
death_year = year(died),
dead = as.integer(!is.na(death_year))
) %>%
mutate(age_at_death = coalesce(death_year, 2020) - birth_year) %>%
survfit(Surv(age_at_death, dead) ~ 1, data = .)
surv_model %>%
plot(main = "K-M Survival of Tour De France Winners")
library(broom)
glance(surv_model) %>% knitr::kable()
records | n.max | n.start | events | rmean | rmean.std.error | median | conf.low | conf.high | nobs |
---|---|---|---|---|---|---|---|---|---|
63 | 63 | 63 | 38 | 69.62491 | 2.685674 | 77 | 71 | 82 | 63 |
Of the 63 Tour De France winners, 38 are still alive. After accounting for survival expectations for the living, the median life expectancy of a Tour de France winner is estimated as 77 years old.
Stage data
p <- stage_data %>%
group_by(decade = 10 * (year %/% 10)) %>%
distinct(rider, edition, age) %>%
ggplot(aes(decade, age)) +
geom_jitter(color = 7, size = 0.5, alpha = 0.1)
p4 <- p +
geom_line(
data = by_decade, aes(decade, winner_age),
color = 8, size = 3, show.legend = FALSE
) +
expand_limits(y = 0) +
labs(
y = "", x = "",
title = "Average Age of Tour de France Winners By Decade",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
p4
stages_joined <- stage_data %>%
tidyr::extract(stage_results_id, "stage", "stage-(.*)") %>%
mutate(
stage = if_else(year %in% 1967:1968 & stage == 0, "1a", stage),
stage = if_else(year %in% 1967:1968 & stage == 1, "1b", stage),
stage = if_else(year %in% 1969:2012 & stage == 0, "P", stage)
) %>%
filter(year < 2018) %>%
left_join(tdf_stages, by = c("year", "stage")) %>%
select(-winner, bib_number, winner_country) %>%
mutate(rank = as.integer(rank)) %>%
group_by(year, stage) %>%
mutate(finishers = sum(!is.na(rank))) %>%
ungroup() %>%
mutate(percentile = 1 - rank / finishers)
p5 <- stages_joined %>%
count(year, stage) %>%
ggplot(aes(n)) +
geom_histogram(fill = 11) +
labs(title = "Number of Stages Joined Each Year")
p5
It appears that some racers are eliminated or drop out as stages are completed
total_points <- stages_joined %>%
group_by(year, rider) %>%
summarize(
total_points = sum(points, na.rm = TRUE),
.groups = "drop"
) %>%
mutate(points_rank = percent_rank(total_points))
Does the winner of the first stage predict their final point ranking?
p6 <- stages_joined %>%
filter(stage == "1") %>%
inner_join(total_points, by = c("year", "rider")) %>%
select(year, rider,
percentile_first_stage = percentile,
points_rank
) %>%
filter(!is.na(percentile_first_stage)) %>%
mutate(first_stage_bin = cut(percentile_first_stage, seq(0, 1, 0.1))) %>%
filter(!is.na(first_stage_bin)) %>%
ggplot(aes(first_stage_bin, points_rank)) +
geom_boxplot(fill = 12) +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
scale_y_continuous(labels = scales::percent) +
labs(
x = "Decile Perforance in the First Stage",
y = "Overall Points Percentile",
title = "Relationship of TDF First Stage Finish w/ Overall Finish",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle",
caption = paste0("@Jim_Gruman | #TidyTuesday | ", Sys.Date())
)
p6
Lets explore the names and life durations of the Tour de France winners
winners <- tdf_winners %>%
select(edition, winner_name, born, died, nickname, nationality, start_date, year) %>%
# factor and reorder the winners by birth date
mutate(winner_name = fct_reorder(winner_name, desc(born))) %>%
# compute a life duration in numeric years
mutate(life_duration = as.numeric(as.duration(ymd(born) %--% ymd(died)), "years")) %>%
filter(!is.na(life_duration))
pal <- RColorBrewer::brewer.pal("Set1", n = 3)
life_wins <- winners %>%
ggplot() +
geom_linerange(aes(
xmin = born,
xmax = died,
y = winner_name,
color = life_duration
),
lwd = 1.1
) +
labs(
x = "",
y = "Year"
) +
geom_point(aes(
y = winner_name,
x = year
),
shape = 19,
size = 2,
color = "grey"
) +
scale_shape_identity("",
labels = "Won the\nTour de France",
breaks = c(19),
guide = "legend"
) +
scale_colour_gradient2("Lifetime\n(years)",
low = pal[1], mid = pal[2],
high = pal[3], midpoint = 60
) +
labs(
title = "Lifespans of Riders",
subtitle = "source: Alastair Rushworths R Data Package tdf and Kaggle"
) +
guides(
colour = guide_legend(order = 1),
shape = guide_legend(order = 2)
) +
theme(
legend.position = "top",
legend.background = element_rect(color = "white")
) +
theme_jim(base_size = 10)
(life_wins | nations) +
plot_annotation("Tour de France Winners") +
theme(aspect.ratio = 3)
The original tweet submission:
tweetrmd::include_tweet("https://twitter.com/jim_gruman/status/1248662506102497281")
#TidyTuesday: Tour de France #rstats #cycling
— Jim Gruman📚🚵♂️⚙ (@jim_gruman) April 10, 2020
Code: https://t.co/PjmnaAGBnE pic.twitter.com/qdwEp9siDL
sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] broom_0.7.9 survival_3.2-11 patchwork_1.1.1 lubridate_1.7.10
[5] rvest_1.0.1 ggtext_0.1.1 paletteer_1.4.0 forcats_0.5.1
[9] stringr_1.4.0 dplyr_1.0.7 purrr_0.3.4 readr_2.0.1
[13] tidyr_1.1.3 tibble_3.1.4 ggplot2_3.3.5 tidyverse_1.3.1
[17] workflowr_1.6.2
loaded via a namespace (and not attached):
[1] readxl_1.3.1 backports_1.2.1 systemfonts_1.0.2
[4] workflows_0.2.3 plyr_1.8.6 selectr_0.4-2
[7] tidytuesdayR_1.0.1 splines_4.1.1 listenv_0.8.0
[10] usethis_2.0.1 digest_0.6.27 foreach_1.5.1
[13] htmltools_0.5.2 yardstick_0.0.8 viridis_0.6.1
[16] parsnip_0.1.7.900 fansi_0.5.0 magrittr_2.0.1
[19] tune_0.1.6 tzdb_0.1.2 recipes_0.1.16
[22] globals_0.14.0 modelr_0.1.8 gower_0.2.2
[25] extrafont_0.17 R.utils_2.10.1 vroom_1.5.4
[28] sysfonts_0.8.5 extrafontdb_1.0 hardhat_0.1.6
[31] rsample_0.1.0 dials_0.0.9.9000 colorspace_2.0-2
[34] textshaping_0.3.5 haven_2.4.3 xfun_0.25
[37] RCurl_1.98-1.4 crayon_1.4.1 jsonlite_1.7.2
[40] iterators_1.0.13 glue_1.4.2 gtable_0.3.0
[43] ipred_0.9-11 R.cache_0.15.0 tweetrmd_0.0.9
[46] Rttf2pt1_1.3.9 future.apply_1.8.1 scales_1.1.1
[49] infer_1.0.0 DBI_1.1.1 showtextdb_3.0
[52] Rcpp_1.0.7 viridisLite_0.4.0 gridtext_0.1.4
[55] bit_4.0.4 GPfit_1.0-8 lava_1.6.10
[58] prodlim_2019.11.13 httr_1.4.2 RColorBrewer_1.1-2
[61] ellipsis_0.3.2 farver_2.1.0 R.methodsS3_1.8.1
[64] pkgconfig_2.0.3 nnet_7.3-16 sass_0.4.0
[67] dbplyr_2.1.1 janitor_2.1.0 utf8_1.2.2
[70] here_1.0.1 labeling_0.4.2 tidyselect_1.1.1
[73] rlang_0.4.11 DiceDesign_1.9 later_1.3.0
[76] munsell_0.5.0 cellranger_1.1.0 tools_4.1.1
[79] cachem_1.0.6 cli_3.0.1 generics_0.1.0
[82] evaluate_0.14 fastmap_1.1.0 ragg_1.1.3
[85] yaml_2.2.1 rematch2_2.1.2 knitr_1.33
[88] bit64_4.0.5 fs_1.5.0 showtext_0.9-4
[91] future_1.22.1 whisker_0.4 R.oo_1.24.0
[94] xml2_1.3.2 compiler_4.1.1 rstudioapi_0.13
[97] png_0.1-7 curl_4.3.2 reprex_2.0.1
[100] lhs_1.1.1 bslib_0.3.0 stringi_1.7.4
[103] highr_0.9 gdtools_0.2.3 hrbrthemes_0.8.0
[106] lattice_0.20-44 Matrix_1.3-4 markdown_1.1
[109] styler_1.5.1 conflicted_1.0.4 vctrs_0.3.8
[112] tidymodels_0.1.3 pillar_1.6.2 lifecycle_1.0.0
[115] furrr_0.2.3 jquerylib_0.1.4 bitops_1.0-7
[118] httpuv_1.6.2 R6_2.5.1 promises_1.2.0.1
[121] gridExtra_2.3 parallelly_1.27.0 codetools_0.2-18
[124] MASS_7.3-54 assertthat_0.2.1 rprojroot_2.0.2
[127] withr_2.4.2 parallel_4.1.1 hms_1.1.0
[130] grid_4.1.1 rpart_4.1-15 timeDate_3043.102
[133] class_7.3-19 snakecase_0.11.0 rmarkdown_2.10
[136] git2r_0.28.0 pROC_1.18.0