using tryCatch() in R to assign error values in loop

无人久伴 提交于 2019-12-13 02:33:39

问题


I am struggling with the instructions for tryCatch() in R. I'm trying to capture the closing price for a ticker.

Case 2 = good case = TickersJuly2 = unique price to ticker relationship

Case 1 = bad case = TickersJuly1 = FABU close price is the repeat of CETX

Case 1 desired output is a 0 for FABU.

library(TTR)
close.price1=NULL
TickersJuly1 <- c('DIT','CETX','FABU')
TickersJuly2<- c('AAPL','A','AA')

for(i in TickersJuly1){
           tryCatch(close <- getYahooData(i,20150727,20150727,'daily',"price"),
               error = function(e) close$Close <- 0,
               warning = function(w) close$Close <- 0,
               finally = function(f) close$Close <- 0)
      close.price <- c(as.character(close$Close),i)
      close.price1 <- rbind(close.price1,close.price)
}

回答1:


I think this works. You should be assigning the result of the tryCatch to a variable.

for(i in TickersJuly1){
    close <- tryCatch(
        getYahooData(i,20150727,20150727,'daily',"price"),
        error = function(e) list(Close=0),
        warning = function(w) list(Close=0),
        finally = function(f) list(Close=0))
    close.price <- c(as.character(close$Close),i)
    close.price1 <- rbind(close.price1,close.price)
}


来源:https://stackoverflow.com/questions/31689648/using-trycatch-in-r-to-assign-error-values-in-loop

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