Multiple if statements in a for loop - R

Viewed 19

I am trying to create a for loop that goes through each URL in (recipe_urls) and if it contains a certain domain, a function I wrote for scraping the recipe off the website will run. I have never tried nesting if statements within a for loop before, so I think that might be the root of the problem.

for (recipe_url in recipe_urls) {
  if ("allrecipes.*" %rin% recipe_urls == "TRUE"){
    scrape_allrecipes(recipe_url)
  }
  if("foodnetwork.*" %rin% recipe_urls == "TRUE"){
    scrape_allrecipes(recipe_url)
  }
}

Note: %rin% is a custom function to return true or false if a partial match (e.g., "allrecipes" is present within the URL):

`%rin%` = function (pattern, list) {
  vapply(pattern, function (p) any(grepl(p, list)), logical(1L), USE.NAMES = FALSE)
}

Interestingly, the allrecipes one works but duplicates everything twice (I have it set to print in a .txt file). However the foodnetwork does not seem to run.

Individually, this works to return recipes from URL:

recipes <- for (recipe_url in recipe_urls) {
  scrape_allrecipes(recipe_url)
}
1 Answers

In my infinite wisdom, I accidentally was calling the same function in the second if statement. Works now, oops!

Related