gpt4 book ai didi

r - 从 R 中的 url 下载多个 .csv

转载 作者:行者123 更新时间:2023-12-02 02:21:14 37 4
gpt4 key购买 nike

我有多个 .csv 数据集,我想上传它们并用不同的名称保存它们。非常感谢。

casualty_2005 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2005-gla-data-extract-casualty.csv", header=T)
casualty_2006 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2006-gla-data-extract-casualty.csv", header=T)
casualty_2007 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2007-gla-data-extract-casualty.csv", header=T)
casualty_2008 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2008-gla-data-extract-casualty.csv", header=T)
casualty_2009 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2009-gla-data-extract-casualty.csv", header=T)
casualty_2010 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2010-gla-data-extract-casualty.csv", header=T)
casualty_2011 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2011-gla-data-extract-casualty.csv", header=T)
casualty_2012 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2012-gla-data-extract-casualty.csv", header=T)
casualty_2013 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2013-gla-data-extract-casualty.csv", header=T)
casualty_2014 <- read.csv("https://tfl.gov.uk/cdn/static/cms/documents/2014-gla-data-extract-casualty.csv", header=T)

最佳答案

类似的问题已被问过很多次,创建一个名称/链接向量,然后在 lapply 循环中读入所有文件。
请注意,read.csv 的默认值为 header = TRUE

url_fmt <- "https://tfl.gov.uk/cdn/static/cms/documents/%04d-gla-data-extract-casualty.csv"
url_years <- 2005:2014
url_vec <- sprintf(url_fmt, url_years)
df_list <- lapply(url_vec, read.csv)
names(df_list) <- url_years

head(df_list[[1]]) # first file, top 6 rows
head(df_list[["2005"]]) # same file
head(df_list$`2005`) # same file

编辑

阅读后doctshind s answer ,我意识到问题是询问如何下载文件,而不是如何读取它们。

有关设置新目录的说明是可选的。

#old_dir <- getwd()
#setwd('~/tmp')

lapply(url_vec, function(x) download.file(x, destfile = basename(x)))
list.files(pattern = '\\.csv')
# [1] "2005-gla-data-extract-casualty.csv"
# [2] "2006-gla-data-extract-casualty.csv"
# [3] "2007-gla-data-extract-casualty.csv"
# [4] "2008-gla-data-extract-casualty.csv"
# [5] "2009-gla-data-extract-casualty.csv"
# [6] "2010-gla-data-extract-casualty.csv"
# [7] "2011-gla-data-extract-casualty.csv"
# [8] "2012-gla-data-extract-casualty.csv"
# [9] "2013-gla-data-extract-casualty.csv"
#[10] "2014-gla-data-extract-casualty.csv"

#setwd(old_dir)

关于r - 从 R 中的 url 下载多个 .csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66399899/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com