r - 如何使用“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 }
}
}
任何人都可以帮我运行循环并在遇到错误时跳过吗?
非常感谢!
解决方案
您可以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
推荐阅读
- java - java.lang.IllegalArgumentException:没有为 id“null”映射 PasswordEncoder
- git - 如何在 GitHub 中不出现 bitbucket-pipelines.yml 的情况下将 Bitbucket 分支同步到 GitHub?
- python-3.x - 将图像转换为 TensorFlow 模型的数组
- geoserver - 在 GeoServer 中生成的 Mapbox 矢量平铺在使用 OpenLayers 时会切断平铺边缘上的标签,但在使用 MapLibre-gl 时不会
- javascript - VS2019 中的 JavaScript
- java - FAILURE:构建失败并出现异常 - 任务“:app:mergeExtDexDebug”执行失败
- mips - 更好的解决方法:B[8] = (i - j) + A[20]?
- r - 将每隔一行添加到新列 - R
- sql - 没有空调的车辆不能有电锁
- javascript - 使用 javascript 函数的变量树数组