MelBourbon
MelBourbon

Reputation: 125

R: Not able to trycatch error with lapply

I have a table with stocks in R where I want to calculate the 6 month return based on tq_get and tiingo API. I wanted to use lapply to fill my table but unfortunately some tickers are not available on tiingo or maybe are wrong which returns an error. With this error the assigned data has less rows then the existing data and lapply is not working. I tried to resolve with tryCatch but it's still not working. What is missing?

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

Upvotes: 1

Views: 481

Answers (2)

MelBourbon
MelBourbon

Reputation: 125

With including is_supported_ticker() from package riingo a workaround is possible to avoid the error message.

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

Upvotes: 0

Charlie Gallagher
Charlie Gallagher

Reputation: 616

You need to move the function inside tryCatch. tryCatch wraps your function and catches errors. This should work.

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

EDIT: @rawr already suggested this in a comment, I just saw. I only added a brief explanation of the function.

Upvotes: 1

Related Questions