Using subset in for loop

Hi,

I'm working on a data-set, in which I would like to run the same analysis (table + graph) on 15 different options. Now I know I could write this code 15 times, for each option. But I was wondering whether I could do this through a for loop in order to reduce repetitive coding.

When I try to make a subset of the main data set based upon QueueDesc matches the p I keep running into Error in aggregate.data.frame(lhs, mf[-1L], FUN = FUN, ...) : no rows to aggregate. However, when I run the same subset but then with df_detail <- subset(df, QueueDesc == "(NL) CS (88503)") I do not experience any issues.

Extract of the code used:

all_queues <- list("(NL) CS (88503)", "(NL) CS (88499)")

for (p in all_queues) {
  df_detail <- subset(df, QueueDesc == p)
  ...
}

Any help would be appreciated!

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Hi!

Thanks for your reaction. In the meantime, I solved my issue while making a reprex.

My solution:

df_obs <- data.frame(stringsAsFactors = FALSE,
                 Fruit = c("Apple", "Apple", "Pear", "Pear", "Banana", "Banana"),
                 Date = c("22/02/2022", "23/02/2022", "22/02/2022", "23/02/2022","22/02/2022", "23/02/2022"),
                 Sold = c(5,3,6,2,8,6)
)

all_fruits <- list("Apple", "Pear", "Banana")

for (i in all_fruits) {
  df_i <- subset(df_obs, Fruit == i)
  print(df_i)
}```

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.