R:无法使用 lapply 尝试捕获错误

R: Not able to trycatch error with lapply

我有一个 table 和 R 中的股票,我想根据 tq_get 和 tiingo API 计算 6 个月 return。我想使用 lapply 来填充我的 table,但不幸的是,有些代码在 tiingo 上不可用,或者可能是错误的,return 是一个错误。由于此错误,分配的数据行数少于现有数据,并且 lapply 不起作用。我尝试用 tryCatch 解决,但它仍然无法正常工作。缺少什么?

today <- Sys.Date()
yesterday <- as.Date(today) - days(1)
before <- as.Date(today) - months(6)

tiingo_api_key('<my API key')
calculate <- function (x) {
  ((tq_get(x, get = "tiingo", from = yesterday, to = yesterday)$adjusted)/(tq_get(x, get = "tiingo", from = before, to = before)$adjusted)-1)
}

top10[20] <- lapply(top10[1], calculate(x) tryCatch(calculate(x), error=function(e) NA))

您需要将函数移到 tryCatch 中。 tryCatch 包装您的函数并捕获错误。这应该有效。

# Old version                   vvvvvv function call in wrong place
top10[20] <- lapply(top10[1], calculate(x) tryCatch(calculate(x), error=function(e) NA))


# Corrected version
top10[20] <- lapply(top10[1], function(x) tryCatch(calculate(x), error=function(e) NA))

编辑:@rawr 已经在评论中提出了这一点,我刚看到。我只是加了一个功能的简单解释。

通过包含包 riingo 中的 is_supported_ticker(),可以采用一种解决方法来避免错误消息。

calculate <- function (x) {
  supported = sapply(x, is_supported_ticker, type = "tiingo")
  result = rep(NA, length(x))
  result[supported] = 
    (
      tq_get(x[supported], get = "tiingo", from = yesterday, to = yesterday)$adjusted / 
      tq_get(x[supported], get = "tiingo", from = before, to = before)$adjusted
    ) - 1
  return(result)
}