使用R中的tryCatch()在循环中分配错误值

时间:2015-07-29 01:08:52

标签: r try-catch

我正在努力处理R中的tryCatch()指令。我试图捕获股票代码的收盘价。

案例2 =好案例= TickersJuly2 =股票关系的唯一价格

案例1 =坏案例= TickersJuly1 = FABU收盘价是CETX的重复

案例1所需的输出对于FABU是0。

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 个答案:

答案 0 :(得分:1)

我认为这很有效。您应该将tryCatch的结果分配给变量。

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