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?