dplyr conditional summarise

Viewed 59

I have a working solution, but is there a cleaner or more efficient one, when summarizing data?

The following data frame:

set.seed(101)
dtf <- data.frame(group=rep(c("A", "B", "C"),each=5),
                  item_id=sample(1:1000,size = 15,replace = F),
                  days_to_sale=sample(1:20,size = 15,replace = T))

I calculate the following table (where counts are cumulative)

group count_items sold_in_1_d sold_in_5_d sold_in_20_d
A 5 0 3 5
B 5 1 1 5
C 5 0 0 5

With this code

dtf%>%
  group_by(group)%>%
  summarise(count_total=n(),
         sold_in_1_d= length(days_to_sale[days_to_sale<=1]),
         sold_in_5_d= length(days_to_sale[days_to_sale<=5]),
         sold_in_20_d= length(days_to_sale[days_to_sale<=20]))

But I would like to change length() to n() and maybe shorten the subsetting?

Are there better, cleaner solutions?

1 Answers

I think adding new variable to dtf instead doing it in summarise part are more simpler to do it:

dtf$day_sale_1 <- dtf$days_to_sale <= 1
dtf$day_sale_5 <- dtf$days_to_sale <= 5
dtf$day_sale_20 <- dtf$days_to_sale <= 20

dtf %>% group_by(group) %>% 
summarise(sold_in_day1 = sum(day_sale_1), 
          sold_in_day5= sum(day_sale_5), 
          sold_in_day20 = sum(day_sale_20))

  group  day1  day5 day20
  <chr> <int> <int> <int>
1 A         0     3     5
2 B         1     1     5
3 C         0     0     5
Related