Struggling with how to combine groups of rows in a data frame

data.table, dataframe, r

Solution

`cut` is a handy tool for this sort of thing. here's one way:

#First make some data to work with 
#I suggest you do this in the future as it makes it 
#easier to provide you with assistance.
set.seed(10)
dat <- data.frame(product_id=1:15, view_count=sample(1:20, 15, replace=T), 
    purchase_count=sample(1:8, 15, replace=T))
dat   #look at the data

#now we can use cut and aggregate by this new variable we just created
dat$view_count_range <- with(dat, cut(view_count, c(0, 10, 20)))
aggregate(purchase_count~view_count_range, dat, sum)

Which yields:

  view_count_range purchase_count
1           (0,10]             39
2          (10,20]             31

Problem

I have a data frame like so ``` product_id view_count purchase_count 1 11 1 2 20 3 3 5 2 ... ``` I would like to transform this into a table that groups by view_count and sums the purchase_count for an interval for instance. ``` view_count_range total_purchase_count 0-10 45 10-20 65 ``` These view_count_ranges will be of fixed size. I would appreciate any suggestions on how to group ranges like this.

Original source