如何在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
- Incorrect List Initialization: Your initial
xwas a fixed-length list of 5 empty lists, which didn't align with the actual length oflangandbm. We now dynamically create lists that match the number of languages and articles you're working with. - Assignment in
tryCatch: Directly assigningx[[i]][[j]]inside thetryCatchexpression isn't the right approach. Instead, we capture the result ofarticle_pageviews(or the error-handled NULL) and assign it after thetryCatchblock. - 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 separatenextstatement.
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
相关产品推荐
相关产品推荐

