簡體   English   中英

如何使用“tryCatch”跳過 R 中嵌套循環中的錯誤?

[英]How to use “tryCatch” to skip errors in a nested loop in R?

我正在嘗試使用pageviews使用嵌套循環加載一些數據。 你已經幫我得到了這個結果:

library("pageviews")

lang = c("it.wikipedia")
bm = c("ECB","Christine Lagarde")

x <- list(
    list(),
    list(),
    list(),
    list(),
    list()
    ) # store results

for (i in seq_along(lang)) {
  for (j in seq_along(bm)) {
        
x[[i]][[j]] = article_pageviews(project = lang[i], article = bm[j], platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily")
  
  }
}

然而,我需要做的最后一步是閱讀一些project不存在的article 在下面找到一個例子:

lang = c("it.wikipedia")
bm = c("Philip Lane")

    
x = article_pageviews(project = lang, article = bm, platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily")
 
# Error in FUN(X[[i]], ...) : 
#  The date(s) you used are valid, but we either do not have data for those date(s), or the project you asked for is not loaded yet.  Please check https://wikimedia.org/api/rest_v1/?doc for more information.

我想將此添加到循環中。 我嘗試了一些解決方案,但如果出現錯誤,我無法讓循環跳過。 我在一個錯誤的嘗試下面發布:

lang = c("it.wikipedia")
bm = c("ECB", "Christine Lagarde", "Philip Lane")

for (i in seq_along(lang)) {
  for (j in seq_along(bm)) {
    
  skip_to_next <- FALSE
    
  tryCatch(x[[i]][[j]] = article_pageviews(project = lang[i], article = bm[j], platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily"), error = function(e) {skip_to_next <<- TRUE})
  
    if(skip_to_next) { next }     

  }
}


任何人都可以幫我運行循環並在遇到錯誤時跳過嗎?

非常感謝!

您可以將tryCatch用作:

library(pageviews)
library(purrr)

lang = c("it.wikipedia")
bm = c("ECB", "Christine Lagarde", "Philip Lane")

map_df(lang, function(x) map_df(bm, function(y) 
  tryCatch(article_pageviews(project = x, article = y, platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily"), 
           error = function(e) {}))) -> result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM