0

一直在尝试使用 quantmod 使用循环分析大量股票。问题是我不知道雅虎是否拥有我需要的所有库存数据,所以我试图对 R 进行编程以在下载失败时跳过错误,但我似乎无法关闭警告消息。在通常的库启动后,我这样做并得到:

> options(show.error.messages = FALSE)  
> getSymbols("gewg", warnings = FALSE)  
Warning message:
In download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  cannot open: HTTP status was '404 Not Found'`

知道为什么会这样吗?

编辑:我已经包含了我用来测试它的代码,可以看出只有 NOTE1 出现,而​​ NOTE2 没有出现。我用 a2 中的工作代码尝试了它,并且 NOTE1 和 NOTE2 都出现了。

> tester2 <- function(){
+ tester <- function() {
+ a <- getSymbols("GOOG", auto.assign = FALSE)
+ cat("NOTE1")
+ a2 <- getSymbols("JWEGOWN", auto.assign = FALSE)
+ cat("NOTE2")
+ a3 <- getSymbols("GS", auto.assign = FALSE)
+ return(a3)
+ }
+ return(try(tester(), TRUE))
+ }
> af <- tester2()
NOTE1Warning message:
In download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  cannot open: HTTP status was '404 Not Found'
> 
4

1 回答 1

1

做这种事情的标准方法是使用try. 这看起来像(来自文档的示例try):

 set.seed(123)
 x <- stats::rnorm(50)
 doit <- function(x)
 {
     x <- sample(x, replace=TRUE)
     if(length(unique(x)) > 30) mean(x)
     else stop("too few unique points")
 }
 ## alternative 1
 res <- lapply(1:100, function(i) try(doit(x), TRUE))

现在的结果res显示正常输出或 class 的对象try-error。可以使用以下方法组合列表:

# Replace the errors by `NULL`
res2 = lapply(res, 
   function(x) 
     if(!inherits(x, "try-error")) 
       return(x) 
     else 
       return(NULL))
resfinal = do.call("c", res2)

resfinal现在是一个列表,其中只有没有失败的结果。

于 2011-12-14T10:27:05.303 回答