首页 > 解决方案 > R中的异常处理-下载正确的数据时返回

问题描述

我在数据集中有以下字段。

Location : Unique location id of place of installation
Serial : Unique serial number of product
Last Report Date : Date of last communication with location

现在只考虑两个地点,每个地点都有两个连续剧。

Location  Serial LDate       SDate
01        1234   2020-02-29  2020-02-20
01        4321   2020-02-29  2020-02-29
02        2143   2020-03-03  2020-03-03
02        1432   2020-03-03  2020-03-03

在此,连续上报日期仅供参考,实际未知。我有一个数据集,每个位置只有一个序列,如下所示:

location serial   SDate
01       1234     2020-02-29
02       1432     2020-03-03

在此数据集中,SDate 是某个位置的所有连续出版物中的最新报告日期。

数据驻留在 S3 存储桶中。url 包含位置和上次报告日期。我正在动态创建 url 以下载数据。网址如下所示:

url for location 01:"s3://xxxx.xxxx.2020/01/readings/01-20200229.csv"
url for location 02:"s3://xxxx.xxxx.2020/02/readings/02-20200303.csv"

我编写了一个函数来下载我的数据集中的连续剧数据。该函数的逻辑如下:

for(i in 1:nrow(dataset)) {
  date = as.Date(paste0(dataset$SDate[[i]]))
  while (!exists("latest")) {
    latest = s3download(dataset$location[[i]], dataset$serial[[i]], date)
    date = date - 1
  }
  if (!exists("data")) {
    data = latest
    rm(latest)
  }
  else if (exists("data")) {
    data = rbind(data, latest)
    rm(latest)
  }
}

该函数如下所示:

s3download = function(location, serial, date) {
  url = paste0(
    "s3://xxxx.xxxx.",
    lubridate::year(date),
    "/",
    location,
    "/readings/",
    location,
    "-",
    gsub("-", "" , as.character(date)),
    ".csv"
  )
  out = tryCatch({
     latestdata = data.frame(aws.s3::s3read_using(read.csv, object = paste(url), header = FALSE))
  }, error = function(cond) {
    message(cond)
    return(NA)
  }, warning = function(cond) {
    message(cond)
    return(NULL)
  },
  finally = {
    message(paste("Dowloaded))
    message("Thank you")
  })
  return(latestdata)
}

上述功能未按应有的方式执行。逻辑不正确。

它应该做的是

1 Pick the first location and date from dataset
2 Call the function to dynamically create a url with the date
3 Download the data from S3
  a Download the data for the above date for the location
  b See if the data for the desired serial is available
  c If not, repeat steps and b for next dates for this location till data for serial is met
- Repeat step 1:3 for next record in dataset

请帮忙。提前致谢。

标签: rfunctionamazon-s3error-handling

解决方案


推荐阅读