即使使用Quantmod的getSymbols遇到错误,也要使lapply继续运行 [英] Have lapply continue even after encountering an error using getSymbols from quantmod
问题描述
我正在使用包裹在lapply语句中的Quantmod从Yahoo Finance下载一些信息:
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))
股票代码为MKQ故意向上。我希望循环打印错误,但仍然使用其他3个行情清单的请求数据创建xts对象的列表。
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.
我尝试如下使用tryCatch但未成功:
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)
关于如何执行此操作的任何建议?我阅读了tryCatch上的文档,但无法理解。
Any suggestions on how to do this? I read the documentation on tryCatch but was not able to make sense of it.
谢谢。
推荐答案
您需要在函数中放置 try
块:
You need to put the try
block inside your function:
quotes <- lapply(tickers, function(x) try(getSymbols(x, ...)))
注意,我们在这里使用更简单的 try
。如果发生错误,您的引用
对象将在导致该元素的元素位置包含 try-error
类的对象错误。
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.
这篇关于即使使用Quantmod的getSymbols遇到错误,也要使lapply继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!