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 following:
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 }, error = function(e) {conditionMessage(e) } )
This is what my professor suggested!