[英]Loop through csv files in R
我需要獲得 2021 年所有一級方程式比賽的結果。在這里,我想遍歷所有這些 url 並閱讀文件。 您可以在下面看到我當前的代碼。 url 幾乎相同,例如只有“http://ergast.com/api/f1/2021/x/driverStandings”中的 x 發生了變化。 有辦法嗎? 非常感謝您!
baseurl = "http://ergast.com/api/f1/2021/"
results
x=1
while (x <= 22)
{
baseurl = baseurl + x + "/driverStandings"
data = GET(baseurl)
x = x+1
}
library(tidyverse)
library(xml2)
get_races <- function(round) {
data <- paste0("https://ergast.com/api/f1/2021/",
round,
"/driverStandings") %>%
read_xml() %>%
xml_ns_strip()
df <- tibble(
position = data %>%
xml_child() %>%
xml_child() %>%
xml_children() %>%
xml_attr("position") %>%
as.numeric(),
name = data %>% xml_find_all(xpath = "//GivenName") %>%
xml_text() %>%
paste(data %>% xml_find_all(xpath = "//FamilyName") %>%
xml_text()),
constructor = data %>%
xml_find_all(xpath = "//Name") %>%
xml_text(),
points = data %>%
xml_child() %>%
xml_child() %>%
xml_children() %>%
xml_attr("points") %>%
as.numeric(),
wins = data %>%
xml_child() %>%
xml_child() %>%
xml_children() %>%
xml_attr("wins") %>%
as.numeric(),
season = data %>%
xml_child() %>%
xml_attr("season") %>%
as.numeric(),
round = data %>%
xml_child() %>%
xml_attr("round") %>%
as.numeric()
)
return(df)
}
獲得從 1 到 22 的所有比賽
all_races <- map_dfr(1:22, get_races)
# A tibble: 450 × 7
position name constructor points wins season round
<dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 1 Lewis Hamilton Mercedes 25 1 2021 1
2 2 Max Verstappen Red Bull 18 0 2021 1
3 3 Valtteri Bottas Mercedes 16 0 2021 1
4 4 Lando Norris McLaren 12 0 2021 1
5 5 Sergio Pérez Red Bull 10 0 2021 1
6 6 Charles Leclerc Ferrari 8 0 2021 1
7 7 Daniel Ricciardo McLaren 6 0 2021 1
8 8 Carlos Sainz Ferrari 4 0 2021 1
9 9 Yuki Tsunoda AlphaTauri 2 0 2021 1
10 10 Lance Stroll Aston Martin 1 0 2021 1
# … with 440 more rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.