Use tryCatch within R loop

被刻印的时光 ゝ 提交于 2019-12-11 03:29:37

问题


I want to read prices and compute returns for data obtained from Yahoo, passing over symbols for which data could not be read. The code

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))
}

does not work, giving output

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

How do I use tryCatch properly?


回答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")
      })
      }



回答2:


If all else fails, follow the examples in ?tryCatch. tryCatch(..., error = function(e) e). error is a function, not an expression.

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))
}


来源:https://stackoverflow.com/questions/29304940/use-trycatch-within-r-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!