Home > Blockchain >  skip an iteration in for-loop in case of an error message
skip an iteration in for-loop in case of an error message

Time:10-11

I am writing a code to scrape data from websites in R where I'm bound to get an error saying no such directory was found.

It is a part of a longer for-loop and in case of error when the loop usually ends itself, I wish to continue the loop but instead, the iteration should move to the next count.

Code:

library(geniusr)

lyrics_list = list(length = nrow(artists))
for(i in 1:50)

{
  counter = 1
  for(j in 1:row(artist_list[[i]]))
  {
    if(error == TRUE)
    {
      counter = j 1
      next
    }
    lyrics_list[[i]][[counter]] <- list(get_lyrics_search(artist_name = artist_list[[i]][counter,1], song_title = artist_list[[i]][counter,30]))
    counter = counter   1
  }
}

This was my earlier approach before I tried my hands with tryCatch()

library(geniusr)

lyrics_list = list(length = nrow(artists))

for(i in 1:50)
{
  counter = 1
  for(j in 1:nrow(artist_list[[i]]))
  {
    tryCatch({lyrics_list[[i]][[counter]] <- list(get_lyrics_search(artist_name = artist_list[[i]][counter,1], song_title = artist_list[[i]][counter,30]))
    counter = counter   1})
  }
}

The expected error message which I'll encounter in the loop is:

Error in open.connection(x, "rb") : HTTP error 404.

In case of the error, I want to move to the next iteration, i.e., increase j or increase I if that's the case

All suggestions for the if() conditional part will be welcomed

CodePudding user response:

Try replacing your trycatch with the fol­lowing:

tryCatch({ ​ ​ ​ lyrics_list­[[i]][[counter]] <- list(get_lyrics_sear­ch(artist_name = art­ist_list[[i]][counte­r,1], song_title = artist_list[[i]][coun­ter,30])) ​ ​ counter = coun­ter 1 ​ ​ }, error = fun­ction(e) {conditionM­essage(e) } ​ ​ )

This is what my professor suggested!

  • Related