R循环在2504中仅完成3次迭代

问题描述 投票:0回答:1

我编写了一个从NOAA的数据库下载多个文件的功能。首先,我有sites,这是我要从网站上下载的站点ID的列表。看起来像这样:

 > head(sites)
   [[1]]
   [1] "9212"

   [[2]]
   [1] "10158"

   [[3]]
   [1] "11098"

> length(sites)
   [1] 2504

我的功能如下所示。

tested<-lapply(seq_along(sites), function(x) {
   no<-sites[[x]]
   data=GET(paste0('https://www.ncdc.noaa.gov/paleo-search/data/search.json?xmlId=', no))
   v<-content(data)   
   check=GET(v$statusUrl)
   j<-content(check)
   URL<-j$archive
   download.file(URL, destfile=paste0('./tree_ring/', no, '.zip'))
 }) 

奇怪的问题是,它适用于前三个站点(正确下载),但是在这三个站点之后停止并抛出以下错误:

Error in charToRaw(URL) : argument must be a character vector of length 1 

我尝试手动下载第4和第5个站点(使用与上述相同的代码,但不在功能内),并且工作正常。这里可能会发生什么?

编辑1:根据要求显示更多站点ID

> dput(sites[1:6])
list("9212", "10158", "11098", "15757", "15777", "15781")
r httr
1个回答
1
投票

我将您的代码转换为for循环,以便在出现故障时可以查看所有变量的最新值。

失败在第四个站点上并不一致。运行几次您的代码,有时它在2或3或4上失败。当它失败时,如果我查看j,我会看到:

$message
[1] "finalizing archive"

$status
[1] "working"
$message
[1] "finalizing archive"

$status
[1] "working"

[如果几秒钟后重新运行check=GET(v$statusUrl); j<-content(check),则会看到

$archive
[1] "https://www.ncdc.noaa.gov/web-content/paleo/bundle/1986420067_2020-04-23.zip"

$status
[1] "complete"

因此,我认为服务器需要一点时间来准备要下载的文件,有时R会在准备好文件之前要求文件,这会导致错误。一个简单的修复可能看起来像这样:

check_status <- function(v) {
  check <- GET(v$statusUrl)
  content(check)
}

for(x in seq_along(sites)) {
   no<-sites[[x]]
   data=GET(paste0('https://www.ncdc.noaa.gov/paleo-search/data/search.json?xmlId=', no))
   v<-content(data)
   try_counter <- 0
   j <- check_status(v)
   while(j$status != "complete" & try_counter < 100) {
     Sys.sleep(0.1)
     j <- check_status(v)
   }
   URL<-j$archive
   download.file(URL, destfile=paste0(no, '.zip'))
}

如果状态尚未就绪,此版本将等待0.1秒,然后再次检查,最多10秒。

© www.soinside.com 2019 - 2024. All rights reserved.