首页 > 解决方案 > 如何使用“tryCatch”跳过 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")
  
  }
}

然而,我需要做的最后一步是阅读一些不存在article的内容。project在下面找到一个例子:

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 }     

  }
}


任何人都可以帮我运行循环并在遇到错误时跳过吗?

非常感谢!

标签: rfor-looptry-catchnested-loopstry-catch-finally

解决方案


您可以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

推荐阅读