【问题标题】:Use tryCatch within R loop在 R 循环中使用 tryCatch
【发布时间】:2015-06-01 00:46:42
【问题描述】:

我想读取从 Yahoo 获得的数据的价格并计算回报,传递无法读取数据的符号。代码

library("TTR")
source("util.r")
symbols =
for (sym in c("CSI","XCSIX","IGI")) {
    cat("\nreading data for",sym,"\n")
    tryCatch(
    {
    stk = getYahooData(sym, start = 20000101, end = 20200101, freq = "daily")
    ndays = length(index(stk))
    logret = ((log(stk$Close) - lag(log(stk$Close)))) [2:ndays]
    print(summary(logret))},
    error = cat("could not read data for ",sym))
}

不起作用,给出输出

reading data for CSI 
could not read data for  CSI     Index                         Close           
 Min.   :2000-01-04 00:00:00   Min.   :-0.1640284  
 1st Qu.:2003-10-27 06:00:00   1st Qu.:-0.0028756  
 Median :2007-08-16 12:00:00   Median : 0.0000000  
 Mean   :2007-08-16 05:37:08   Mean   : 0.0003147  
 3rd Qu.:2011-06-05 06:00:00   3rd Qu.: 0.0037004  
 Max.   :2015-03-26 00:00:00   Max.   : 0.2523210  

reading data for XCSIX 
could not read data for  XCSIXError in tryCatchOne(expr, names, parentenv, handlers[[1L]]) : 
  attempt to apply non-function
Calls: tryCatch -> tryCatchList -> tryCatchOne
In addition: Warning message:
In file(file, "rt") : cannot open: HTTP status was '404 Not Found'
Execution halted

如何正确使用 tryCatch?

【问题讨论】:

    标签: r exception try-catch


    【解决方案1】:
    # This may work    
    library("TTR")
        source("util.r")
        symbols =
          for (sym in c("CSI","XCSIX","IGI")) {
            cat("\nreading data for",sym,"\n")
            tryCatch(
              {
                stk = getYahooData(sym, start = 20000101, end = 20200101, freq = "daily")
                ndays = length(index(stk))
                logret = ((log(stk$Close) - lag(log(stk$Close)))) [2:ndays]
                print(summary(logret))},
              error=function(err) {
                cat("Data doesn't exist for company:", sym, "and the error is", conditionMessage(err), "\n")
          })
          }
    

    【讨论】:

    • 感谢您和 Joshua Ulrich。我现在明白了。
    【解决方案2】:

    如果一切都失败了,请按照?tryCatch 中的示例进行操作。 tryCatch(..., error = function(e) e)error 是一个函数,而不是一个表达式。

    library("TTR")
    for (sym in c("CSI","XCSIX","IGI")) {
      cat("\nreading data for",sym,"\n")
      tryCatch(getYahooData(sym, start=20000101, end=20200101),
               error = function(e) cat("could not read data for ",sym))
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      相关资源
      最近更新 更多