如何使用"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")

}
}

然而,我需要做的最后一步是读取一些不存在projectarticle。下面的例子:

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

最新更新