Quantmod 错误处理不正确的代码

Quantmod Error Handling Incorrect Tickers

我有一个股票行情列表,我想遍历并获取调整后的历史收盘价。之后我会将输出绑定在一起。但是,如果由于其中一个代码不正确而发现错误,我想 (i) 跳过并获取下一个代码或 (ii) 将该代码捕获为错误。这是一些玩具代码:

require(quantmod)

symbols <- c("KO","FANATASTICALLYCOOL","MSFT","LUCKYDEVIL","LMT")
getSymbols(symbols, from="1990-01-01")
prices <- list()
for(i in 1:length(symbols)) {
    prices[[i]] <- try(Ad(get(symbols[i])))
}

prices <- do.call(cbind, prices)
colnames(prices) <- gsub("\.[A-z]*", "", colnames(prices))

很明显,FANTASTICALLYCOOL 和 LUCKYDEVIL 不是真正的代码,但奇怪的是,没有出现错误。事实上,这就是我得到的 head(prices)

              KO   FANATASTICALLYCOOL     MSFT       LUCKYDEVIL   LMT
1990-01-02 2.737389    2.737389          0.418482   0.418482    5.970848  
1990-01-03 2.697907    2.697907          0.420840   0.420840    5.934217
1990-01-04 2.684747    2.684747          0.433218   0.433218    5.915902
1990-01-05 2.662812    2.662812          0.422608   0.422608    6.080741
1990-01-08 2.719841    2.719841          0.429092   0.429092    6.025795
1990-01-09 2.697907    2.697907          0.427913   0.427913    5.989164

FANTASTICALLYCOOL 和 LUCKYDEVIL 正在采用前面代码的值。我要么希望 R 跳过自动收报机,要么输入一列全是 NA 的内容。

我试过同时使用 try() 和 tryCatch() 都无济于事。

getSymbols 应该抛出错误。尝试

symbols <- c("KO","FANATASTICALLYCOOL","MSFT","LUCKYDEVIL","LMT")
out <- sapply(symbols, function(s) tryCatch({
  getSymbols(s , env = NULL)
  }, error = function(e) NA)
)

dd <- lapply(out, function(x) if (any(is.na(x))) NA else Ad(x))
dd <- do.call(cbind, dd)
#            KO.Adjusted FANATASTICALLYCOOL MSFT.Adjusted LUCKYDEVIL LMT.Adjusted
# 2007-01-03    18.03268                 NA      23.47842         NA     66.64122
# 2007-01-04    18.04010                 NA      23.43910         NA     66.46724
# 2007-01-05    17.91389                 NA      23.30543         NA     66.70646
# 2007-01-08    18.02896                 NA      23.53346         NA     67.91707
# 2007-01-09    18.04381                 NA      23.55704         NA     67.85182
# 2007-01-10    18.06979                 NA      23.32116         NA     68.56224