繁体   English   中英

for 循环中的多个 if 语句 - R

[英]Multiple if statements in a for loop - R

我正在尝试创建一个 for 循环,该循环遍历(recipe_urls)中的每个 URL,如果它包含某个域,则我为从网站上抓取食谱而编写的 function 将运行。 我以前从未尝试在 for 循环中嵌套 if 语句,所以我认为这可能是问题的根源。

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)
  }
}

注意%rin%是一个自定义 function 如果部分匹配(例如,“allrecipes”存在于 URL 中),则返回 true 或 false:

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

有趣的是,allrecipes 一个有效,但将所有内容复制了两次(我将其设置为在 a.txt 文件中打印)。 然而,食品网络似乎没有运行。

单独地,这可以从 URL 返回食谱:

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

在我无限的智慧中,我不小心在第二个 if 语句中调用了相同的 function。 现在工作,哎呀!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM