-
Notifications
You must be signed in to change notification settings - Fork 0
/
afltables.rmd
58 lines (53 loc) · 1.76 KB
/
afltables.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
---
---
The easiest way to get the results of past AFL matches in bulk is from [afltables.com](https://afltables.com/afl/seas/2018.html). They aren't in a format particularly amenable to analysis, so a little bit of work needs to be done in wrangling the online tables into data frames:
```{r,message=FALSE}
library(tidyverse)
library(rvest)
season <- read_html('https://afltables.com/afl/seas/2017.html')
```
```{r}
process_match_description <- function(x){
home_team <- x[1,1]
away_team <- x[2,1]
home_score <- x[1,3]
away_score <- x[2,3]
metadata_string <- x[1,4] #includes date, time, attendance, venue
venue <- str_extract(metadata_string,'Venue:.*$') %>%
str_replace('Venue: ','')
attendance <- str_extract(metadata_string,'Att: [0-9,]+') %>% str_replace('Att: ','') %>% str_replace(',','') %>% as.numeric()
date <- str_extract(metadata_string,'[0-9]{1,2}-[A-Z][a-z]{2}-[0-9]{4}') %>% lubridate::dmy()
tibble(home=home_team,away=away_team,home_score=home_score,away_score=away_score,venue=venue,attendance=attendance,date=date)
}
```
```{r}
get_season_results <- function(year){
url <- paste0('https://afltables.com/afl/seas/',year,'.html')
season <- read_html(url)
results <- html_table(season,fill=TRUE)
results <- results %>%
keep(~all(dim(.x)==c(2,4))|all(dim(.x)==c(1,2))|all(dim(.x)==c(1,1)))
i <- 1
output <- list()
round <- ''
for (result in results){
if (all(dim(result)==c(1,2))){
round <- result[1,1]
}
if (all(dim(result) == c(1,1))){
round <- result[1,1]
}
if (all(dim(result)==c(2,4))){
output[[i]] <- process_match_description(result)
output[[i]]$round <- round
i <- i+1
}
}
bind_rows(output)
}
```
```{r}
results <- map(2010:2018,get_season_results) %>%
bind_rows
as.data.frame(results)
```