You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言嵌套循环中使用tryCatch跳过pageviews包数据加载错误?

Handling Errors in Nested Loops for the pageviews Package in R

Let's fix your nested loop with proper error handling so it skips articles that fail to load. Here's the revised code that works as intended:

library("pageviews")
library(lubridate) # Required for the `today()` function

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

# Dynamically initialize the result list to match the length of `lang` and `bm`
x <- vector("list", length(lang))
for (i in seq_along(lang)) {
  x[[i]] <- vector("list", length(bm))
}

for (i in seq_along(lang)) {
  for (j in seq_along(bm)) {
    # Use tryCatch to attempt loading and handle errors gracefully
    pageview_data <- tryCatch(
      expr = {
        article_pageviews(
          project = lang[i], 
          article = bm[j], 
          platform = "all", 
          user_type = "user", 
          start = "2015100100", 
          end = today(), 
          reformat = TRUE, 
          granularity = "daily"
        )
      },
      error = function(e) {
        # Print a helpful message to track which articles failed
        message(sprintf("Skipping article '%s' on %s: %s", bm[j], lang[i], e$message))
        # Return NULL as a placeholder for failed entries
        return(NULL)
      }
    )
    
    # Assign the result (either valid data or NULL) to your list
    x[[i]][[j]] <- pageview_data
  }
}

Why Your Original Attempt Didn't Work

  1. Incorrect List Initialization: Your initial x was a fixed-length list of 5 empty lists, which didn't align with the actual length of lang and bm. We now dynamically create lists that match the number of languages and articles you're working with.
  2. Assignment in tryCatch: Directly assigning x[[i]][[j]] inside the tryCatch expression isn't the right approach. Instead, we capture the result of article_pageviews (or the error-handled NULL) and assign it after the tryCatch block.
  3. Scope Issues with skip_to_next: Using <<- to modify a global variable can lead to unexpected behavior. Instead, we use the error handler to return a placeholder value (NULL) which makes skipping implicit—no need for a separate next statement.

Bonus: Cleaning Up Results

If you want to remove the NULL entries later to keep only valid data, you can use this snippet:

# Filter out NULL entries for each language
cleaned_x <- lapply(x, function(lang_list) Filter(Negate(is.null), lang_list))

内容的提问来源于stack exchange,提问作者Rollo99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 11:17:47