I have this example data frame.
df <- data.frame (MARKET = c("US", "US", "UK", "UK", "China", "China", "Brazil", "Brazil", "US", "US", "UK", "UK", "China", "China", "Brazil", "Brazil","US", "US", "UK", "UK", "China", "China", "Brazil", "Brazil","US", "US", "UK", "UK", "China", "China", "Brazil", "Brazil","US", "US", "UK", "UK", "China", "China", "Brazil", "Brazil"),
MEAL = c("Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner","Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner", "Breakfast")
)
And I want to create separate subsets of the data frame that contain each combination of the meals and markets (i.e. Brazil_Breakfast, Brazil_Lunch, Brazil_Dinner, etc).
I take the row names from each variable here.
markets <- rownames(table(df$MARKET))
meals <- rownames(table(df$MEAL))
I know I can subset one of these like so
brazil_breakfast <- subset(df, MARKET==markets[1] & MEAL==meals[1])
But I would like to be able to automate this. Here's the draft of the for loop I drafted.
for (i in length(markets)) {
for (j in length(meals)) {
i_j <- subset(df, MARKET==markets[i] & MEAL==meals[j])
}
}
But this only creates the last combination, US and Lunch, and it's actually, literally named i_j.
How do I create a separate, new data frames via for loops? Also happy to use an apply statement.
Thank you!