0

I have a list of categories and I can get the number of apps for each category in this list. I'd like to find the 10 categories that have the most apps. I wrote this code which does not work right now, I'm getting this error:

 Error in if (for (topCategoryNb in top10Nb) { : 
  argument is of length zero

So I'm assuming this is because a for loop cannot be put as an argument in an if statement. Is there a better way to do what I'm trying to do? If not how can I fix my code?

Here is the code:

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

The function numberAppPerCategories return the number of apps a category has. For example, for the category "MEDICAL" we will get: (we have 0 as a second argument because that's the starting point of counting in the loop that's in the function but you can just ignore that)

> numberAppPerCategories("MEDICAL",0)
[1] 277
Soffamumie
  • 95
  • 1
  • 7
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 18 '20 at 23:31
  • Thanks I've edited my code so it will be easier to run it! – Soffamumie Oct 18 '20 at 23:36
  • We can't run your code with the `numberAppPerCategories` function. Can you at least tell us about it? Is it vectorized? – Gregor Thomas Oct 18 '20 at 23:37
  • I've edited my question with more details and an example, i hope it's clearer. And I must say that I don't really know if it's vectorised or not.. – Soffamumie Oct 18 '20 at 23:43

1 Answers1

1

Without sample data to test this, it's not very clear what this code is trying to do. If I understand correctly, you don't really need for or if loops. You can probably get the counts for all the categories with

counts <- sapply(allCategories, numberAppPerCategories, 0)

And then you could get the top 10 with

top10  <- head(allCategories[order(-counts)], 10)
MrFlick
  • 195,160
  • 17
  • 277
  • 295