Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中的if语句中使用for循环作为参数_R_Loops_If Statement - Fatal编程技术网

在R中的if语句中使用for循环作为参数

在R中的if语句中使用for循环作为参数,r,loops,if-statement,R,Loops,If Statement,我有一个类别列表,我可以得到该列表中每个类别的应用程序数量。我想找出应用最多的10个类别。 我写的这段代码现在不起作用,我得到了以下错误: Error in if (for (topCategoryNb in top10Nb) { : argument is of length zero 所以我假设这是因为for循环不能作为if语句中的参数。 有没有更好的方法来做我想做的事?如果没有,我如何修复我的代码 代码如下: allCategories <- list("MEDI

我有一个类别列表,我可以得到该列表中每个类别的应用程序数量。我想找出应用最多的10个类别。 我写的这段代码现在不起作用,我得到了以下错误:

 Error in if (for (topCategoryNb in top10Nb) { : 
  argument is of length zero
所以我假设这是因为for循环不能作为if语句中的参数。 有没有更好的方法来做我想做的事?如果没有,我如何修复我的代码

代码如下:

allCategories <- list("MEDICAL", "MAPS_AND_NAVIGATION", "NEWS_AND_MAGAZINES", "VIDEO_PLAYERS", "VIDEO_PLAYERS", 
                     "SOCIAL", "SHOPPING", "PHOTOGRAPHY", "SPORTS", "TRAVEL_AND_LOCAL", "TOOLS", "PERSONALIZATION",
                     "HEALTH_AND_FITNESS", "HOUSE_AND_HOME", "EVENTS")
    top10 <- list()
    top10Nb <- list()
    for(category in allCategories){
      currentNb<- numberAppPerCategories(category,0)
      print(category)
      print(currentNb)
      if(
        for(topCategoryNb in top10Nb){topCategoryNb<currentNb}
      ){
        top10 <- c(top10, category)
      }
      allCategories[- category]  
    }

如果没有样本数据来测试这一点,就不太清楚这段代码试图做什么。如果我理解正确,您不需要对或If循环使用
。您可能可以使用

counts <- sapply(allCategories, numberAppPerCategories, 0)

计数如果您包含一个简单的示例输入和所需的输出,可以用来测试和验证可能的解决方案,那么就更容易帮助您了。谢谢我编辑了我的代码,这样运行起来就更容易了!我们无法使用
numberApperCategories
函数运行您的代码。你至少能告诉我们这件事吗?它是矢量化的吗?我用更多的细节和一个例子编辑了我的问题,我希望它更清晰。我必须说我真的不知道它是不是矢量化了。。
counts <- sapply(allCategories, numberAppPerCategories, 0)
top10  <- head(allCategories[order(-counts)], 10)