I've written a nested for loop and want to convert it to a function. This is the code I currently have:
## Sleeper function
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
## Set up null objects to fill in loop
episodes = NULL
l = NULL
## Scrape pages and append together
for (season in c(27:38)){
for (episode in c(1:13)){
tryCatch({
if (season == 34 & episode == 3){
l = 'l'
}
new_episode <- read_html(paste0('http://www.chakoteya.net/DoctorWho/', season, '-', episode, '.htm', l)) %>%
html_nodes("p") %>%
html_text() %>%
tibble(value = .)
episodes <- episodes %>% bind_rows(new_episode)
cat(paste('\rseason = ', season, '; episode = ', episode))
testit(2)
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
}
As you can see it's looping over seasons 27-38 and within each season episodes 1-13. Sometimes the season only has 12 episodes, hence the tryCatch(). And, for reasons I don't understand, sometimes the URL requires an .html suffix (if season >= 34 and episode >= 3) and sometimes it requires an .htm suffix, hence the if (season == 34 & episode == 3) statement.
I would like to convert this into a function, maybe using apply() or map() but my function skills are still pretty elementary and i'm struggling.
As an end output it'd be great to call a function called, say, doctor_who() like this:
episodes <- doctor_who(season = c(27:38), episode = c(1:13))