2

I am downloading some information from yahoo finance using quantmod wrapped in an lapply statement:

require(quantmod)
tickers <- c("AAPL", "MSFT", "MKQ", "TSLA")
quotes <- lapply(tickers,function(x) getSymbols(x, src="yahoo", from="2015-02-01", auto.assign=FALSE)) 

The ticker MKQ is made up intentionally. I would like the loop to print the error but still create a list of xts objects with the requested data for the other 3 tickers.

I have tried to use tryCatch as follows but was unsuccessful:

quotes <- tryCatch(lapply(tickers,function(x) getSymbols(x, 
src="yahoo", from="2015-02-01", auto.assign=FALSE)) , error=function(e) NULL)

Any suggestions on how to do this? I read the documentation on tryCatch but was not able to make sense of it.

Thank you.

mks212
  • 901
  • 1
  • 18
  • 40
  • How were you able to find the duplicate? nrussell, was it because you answered it? I did do a search, but used terms "lapply", "error" and "continue" which are not in the title of the initial post. Thanks. – mks212 Feb 09 '15 at 22:13

1 Answers1

5

You need to put the try block inside your function:

quotes <- lapply(tickers, function(x) try(getSymbols(x, ...)))

Note we use the simpler try here. If there is an error, your quotes object will contain an object of try-error class at location of element that caused the error.

BrodieG
  • 51,669
  • 9
  • 93
  • 146