1

I have a following dataframe:

data = data.frame(fruit=c('apple','orange','orange'), price=c(2,6,5), 
                  qty=c(30,20,40), brand=c('good', 'decent', 'good'))
   fruit price qty  brand
1  apple     2  30   good
2 orange     6  20 decent
3 orange     5  40   good

I need to group by fruit and minimum price for that fruit and also want to get the corresponding values in qty and brand columns. How should I do that? It sounds simple but I can't figure it out. I can't seem to think further than this which obviously won't work here

library(dplyr)
data %>% 
  group_by(fruit, qty, brand) %>% 
  summarise(min_price = min(price))

Output I would like is this

   fruit price qty  brand
   apple     2  30   good
  orange     5  40   good
horse
  • 78
  • 5

1 Answers1

2

you may try

data %>%
  group_by(fruit) %>%
  filter(price == min(price))


# A tibble: 2 x 4
# Groups:   fruit [2]
  fruit  price   qty brand
  <chr>  <dbl> <dbl> <chr>
1 apple      2    30 good 
2 orange     5    40 good
Park
  • 14,771
  • 6
  • 10
  • 29