Suppose I have the following list of websites - there are 3 "good websites" (that work) and 2 "bad websites" (that don't work - this will "crash" the LOOP). This looks something like this:
# list of website (called "links"):
head(links)
[1] "https://www.good_website_1.com"
[2] "https://www.bad_website_1.com"
[3] "https://www.good_website_2.com"
[4] "https://www.good_website_3.com"
[5] "https://www.bad_website_2.com"
> summary(links)
Length Class Mode
5 character character
> str(links)
chr [1:352] "https://good_website_1.com/" ...
For these links, I am running the following LOOP:
length = length(links)
results <- list()
for (i in 1:length)
{
url_i<-links[i]
page_i <-read_html(url_i)
b_i = page_i %>% html_nodes("div.one_third")
listanswer_i <- b_i %>% html_text() %>% strsplit("\\n")
mx_i <- max(sapply(listanswer_i , length))
df_i <- do.call(rbind , lapply(listanswer_i , \(x) if(length(x) == mx_i) x
else c(x , rep(NA , mx_i - length(x)))))
df_i <- data.frame(df_i)
results[[i]] <- df_i
print(results)
}
The above code will always "crash (i.e. break)" since there are websites that do not work:
Error in data.frame(...)
arguments imply differing number of rows: 1, 0
Normally, I fix this by manually selecting the "good" links - and then re-run the LOOP for these "good links":
good_list = links[c(1,3,4)]
links = good_list
length = length(links)
results <- list()
for (i in 1:length)
{
url_i<-links[i]
page_i <-read_html(url_i)
b_i = page_i %>% html_nodes("div.one_third")
listanswer_i <- b_i %>% html_text() %>% strsplit("\\n")
mx_i <- max(sapply(listanswer_i , length))
df_i <- do.call(rbind , lapply(listanswer_i , \(x) if(length(x) == mx_i) x
else c(x , rep(NA , mx_i - length(x)))))
df_i <- data.frame(df_i)
results[[i]] <- df_i
print(results)
}
My Question: But could something have been done that "forces" the LOOP to keep running and simply place a "row of NA's" in the "results data frame" when a "bad website" is encountered? This would save me the time of manually scanning through the original list of links and testing if each link is "good" or "bad".