我有以下代码将链接下载到相应的文件夹>子文件夹中。这段代码虽然很慢,但效果很好。我有几百个 .zip 文件,我正在尝试下载以便对其进行处理。
在国家数据的文件夹和子文件夹结构中,一些国家可能有 1 个子文件夹,而另一些国家可能有多个子文件夹。
为了模仿现有条件,我还在下面附上了一些虚拟代码:
library("furrr")
library("curl")
country.year.dir <- c("/test/GB/GB_2010", "/test/GB/GB_2014", "/test/GN/GN_2016",
"/test/GY/GY_2000", "/test/GY/GY_2006-2007", "/test/GY/GY_2014")
my.country.names_DTs$URL <- c("https://GB 2010 Datasets.zip",
"https://GB 2014 Datasets.zip", "https://GN 2016 Datasets.zip",
"https://GY 2006-2007 Datasets.zip", "https://GY 2014 Datasets.zip")
my.country.names_DTs$URL_Clean <- c("https://GB_2010_Datasets.zip",
"https://GB_2014_Datasets.zip", "https://GN_2016_Datasets.zip",
"https://GY_2006-2007_Datasets.zip", "https://GY_2014_Datasets.zip")
for(i in seq(country.year.dir)){
setwd(country.year.dir[i])
my.shortcut.2 <- curl_download(my.country.names_DTs[i]$URL, destfile =
my.country.names_DTs[i]$URL_Clean)
}
我搜索了加快下载链接过程的方法,我遇到了这个答案:如何配置未来以下载更多文件?
我已经修改了该代码以适应我的独特情况;但是,下面的代码不起作用。我收到一条错误消息。
download_template <- function(.x) {
for(i in seq(country.year.dir)) {
my.shortcut.2 <- curl_download(url =
my.country.names_DTs[i]$URL, destfile = my.country.names_DTs[i]$URL_Clean)
}
}
download_future_core <- function() {
plan(multiprocess)
future_map(my.country.names_DTs$URL, download_template)
}
download_future_core()
有没有办法加速有效的代码,以便保留相同的功能?
谢谢你。
更新
我没有尝试使用furrr
,而是使用foreach
. 修改后的代码如下:
library("foreach")
library("curl")
import::from(future, plan, cluster)
import::from(doParallel, registerDoParallel)
import::from(snow, stopCluster)
import::from(parallel, makeCluster, detectCores)
cl <- makeCluster(detectCores())
plan(strategy = "cluster", workers = cl)
registerDoParallel(cl)
download_MICS_files <- foreach(i = seq(country.year.dir_MICS)) %dopar% {
currDir <- getwd()
on.exit(setwd(currDir))
setwd(country.year.dir_MICS[i])
MICS_downloaded <- curl_download(my.country.names_MICS_DTs[i]$URL, destfile =
my.country.names_MICS_DTs[i]$URL_Clean)
}
正如我以前(并且仍在收到)foreach
循环中的此错误消息一样:
Error in { : task 1 failed - "cannot change working directory"
我搜索了有关 setwd 和foreach
循环的帮助。我遇到了以下答案:
我使用了该答案中的几行,但我仍然收到相同的错误消息。
在工作目录之间导航的最佳方法是什么,以便foreach
构造与带有 setwd() 错误消息的普通 for 循环一样工作?
谢谢你。