微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

r-使用foreach将多个文件下载到单独的子文件夹中-setwd

如何解决r-使用foreach将多个文件下载到单独的子文件夹中-setwd

我有以下代码链接下载到相应的文件夹>子文件夹中。该代码虽然非常慢,但效果很好。我尝试下载数百个.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)
}

搜索了加快链接下载过程的方法,然后遇到了以下答案:How can I configure future to download more files?

我已修改代码以适合我的独特情况;但是,下面的代码不起作用。我收到错误消息。

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循环的帮助。我遇到了以下答案:

How to change working directory in asynchronous futures in R

我从该答案中使用了两行,但仍收到相同的错误消息。

在工作目录之间导航的最佳方法是什么,以使foreach构造与带有setwd()错误消息的普通for循环一起工作?

谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。