【问题标题】:R: Not able to trycatch error with lapplyR:无法使用 lapply 尝试捕获错误
【发布时间】:2021-01-06 20:47:50
【问题描述】:

我有一张 R 中股票的表格,我想根据 tq_get 和 tiingo API 计算 6 个月的回报。我想用 lapply 来填满我的桌子,但不幸的是,tiingo 上没有一些代码,或者可能是错误的,这会返回错误。由于此错误,分配的数据的行数少于现有数据,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))

【问题讨论】:

  • 你的循环应该类似于lapply(top10[1], function(x) tryCatch(calculate(x), error=function(e) NA))
  • 使用top10[20] &lt;- lapply(top10[1], calculate(x) tryCatch(calculate(x), error=function(e) NA)) 时出现语法错误,calculate(x) 后面缺少,

标签: r lapply


【解决方案1】:

您需要将函数移入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 已经在评论中提出了这个建议,我刚刚看到了。我只添加了函数的简要说明。

【讨论】:

  • 谢谢,但即使有了这个更正,我也会收到以下错误&lt;error/tibble_error_assign_incompatible_size&gt; Assigned data `lapply(top10[1], function(x) tryCatch(calculate(x), error = function(e) NA))` must be compatible with existing data. x Existing data has 14 rows. x Assigned data has 13 rows. ℹ Only vectors of size 1 are recycled. 所以tryCatch 似乎在这里不起作用。
  • 很难说问题出在哪里。看看您是否可以使用类似数据制作一个可重现的示例(最好是不需要 API 密钥的示例)并将其添加到您的问题中。但似乎错误在于分配,而不是 API 抛出的错误,所以tryCatch 工作正常。我不太了解您的数据结构。
  • 我试图创建一个可重现的示例,但不幸的是,如果没有 API 密钥,这是不可能的,因为 tq_get 雅虎数据无法提供所需的结果。
  • 我现在使用包riingo 中的函数is_supported_ticker() 应用了解决方法。
【解决方案2】:

通过从包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)
}

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    相关资源
    最近更新 更多