简体   繁体   English

循环遍历 R 中的 csv 文件

[英]Loop through csv files in R

I need to get the results from all formula 1 races from the year 2021. Here I would like to loop through all of these url's and read the files.我需要获得 2021 年所有一级方程式比赛的结果。在这里,我想遍历所有这些 url 并阅读文件。 You can see my current code below.您可以在下面看到我当前的代码。 The url's are nearly the same, only the x here "http://ergast.com/api/f1/2021/x/driverStandings" changes for example. url 几乎相同,例如只有“http://ergast.com/api/f1/2021/x/driverStandings”中的 x 发生了变化。 Is there a way to?有办法吗? Thank you very much in advance!非常感谢您!

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)
}

Get all races from 1 to 22获得从 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM