0

I have a df with below columns:

first_Date   Profit  Quantity  Discount  Segment
2012-01-01    23       24        45        seg1
2019-01-01    45       33        99        seg2 and so on

I perform groupby on first date column and find sum of profits, sum of quanitites, sum of discounts and most frequenct value of segment. Code made so far:

  group2<-df %>%
  mutate(date = as.Date(first_date), 
         year_mon = format(first_date, "%Y-%m")) %>%
  group_by(first_date) %>%
  summarise(sum_profit = sum(Profit), 
            sum_quantity = sum(Quantity), 
            sum_discount = sum(Discount),
            )

Last column segment has not been captured here. I want to include the most frequent value of segment corresponding to each date above. How to do that

noob
  • 3,601
  • 6
  • 27
  • 73
  • Does this answer your question? [Is there a built-in function for finding the mode?](https://stackoverflow.com/questions/2547402/is-there-a-built-in-function-for-finding-the-mode) – Edward Apr 13 '20 at 15:56
  • Pls fit the same thing inside this code..Unable to do that...I need the mode to be inside the code block...I dont know how to embed the function inside this block – noob Apr 13 '20 at 15:59
  • `mode_segment=Mode(Segment)` – Edward Apr 13 '20 at 16:03
  • mode does not work – Prahlad Apr 14 '20 at 09:02
  • one option,df %>% group_by(first_Date) %>% count(Segment)%>% slice(which.max(n)) – Prahlad Apr 14 '20 at 09:06
  • you can use this link too,https://stackoverflow.com/questions/29922195/return-most-frequent-string-value-for-each-group – Prahlad Apr 14 '20 at 09:11

0 Answers0