0

Here is my dataframe:

df <- structure(list(Location = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
                                            3L, 3L, 3L), .Label = c("buildinga", "buildingb", "buildingc"), class = "factor"), Category = structure(c(1L, 1L, 2L, 1L, 
                                                                                      2L, 1L, 2L, 2L, 1L), .Label = c("Food", "Beverage", "Food"), 
                                                                                       class = "factor"), 
                     units_sold = c(200, 250, 150, 180, 200, 80, 140, 200, 210)), class = "data.frame", row.names = c(NA, 
                                                                                                                    -9L))



print(df)

Location Category units_sold
1 buildinga     Food        200
2 buildinga     Food        250
3 buildinga Beverage        150
4 buildingb     Food        180
5 buildingb Beverage        200
6 buildingb     Food         80
7 buildingc Beverage        140
8 buildingc Beverage        200
9 buildingc     Food        210

I would like to pull the top two values from units sold for both Beverage and Food for each location. This will tell me what the top two grouped products are per location when looking at units sold.

I was trying this if-else statement but did not get any output:


ifelse(Location == Location & Category == Category & units_sold == max(units_sold), new_df

I tried using group_by with arrange order but I could not get the output I wanted. Goal is to export the 2 items per location as a csv file.

Dinho
  • 704
  • 4
  • 15
  • 1
    You example doesn't have sufficient data but I think you need `df %>% group_by(Location, Category) %>% top_n(2, units_sold) ` in `dplyr` – Ronak Shah Nov 22 '19 at 01:06
  • @Ronak Shah I tried that - however my condition needs to give the the top food AND beverage item. When I run this it just gives the top two items, regardless of category factored in to give the top Food and top Bev item...I'm working on a while statement but not sure if something else would be easier to adjust the group_by statement.. – Dinho Nov 22 '19 at 20:08
  • Can you show expected output for the example you have shared ? – Ronak Shah Nov 23 '19 at 00:45

0 Answers0