Search code examples
rfor-loopwikipedia-api

How to skip an item in a loop in R if it returns an error?


I'm trying to download wikipedia pages for a list of names. Not all the names on the list have a wiki page though. I want to loop through the list, save the pages that exist and skip past the names that do not. Is there a way to do this?

Here's where I got to:

library('WikipediR')

names_dat = data.frame(name = c('Donald Trump', 'Jo Biden', 'Fakey McNotreal', 'Bernie Sanders')

wiki_list = list()

for (i in 1:nrow(names_dat)){
  temp = page_content(domain = 'wikipedia.org',
                      page_name = names_dat$name[i],
                      as_wikitext = F)
  wiki_list[[i]] = temp
}

Thanks!


Solution

  • See comments as potential duplicate but I think this is what you are after:

    library('WikipediR')
    
    names_dat = data.frame(name = c('Donald Trump', 'Jo Biden', 'Fakey McNotreal', 'Bernie Sanders'))
                           
    wiki_list = list()
    
    for (i in 1:nrow(names_dat)){
      tryCatch({
        temp = page_content(domain = 'wikipedia.org',
                            page_name = names_dat$name[i],
                            as_wikitext = F)
        wiki_list[[i]] = temp
      }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
    
    }