How do I split values into equal ranges in one column and sum the associated value of another column in R? -


i have dataframe named cust_amount follows:

age    amount_spent 25       20 43       15 32       27 37       10 45       17 29       10 

i want break down equal sized age groups , sum amount spent each age groups given below:

age_group  total_amount  20-30     30  30-40     37  40-50     32 

we can use cut group 'age' , sum of 'amount_spent' based on grouping variable.

library(data.table) setdt(df1)[,.(total_amount = sum(amount_spent)) ,         = .(age_group = cut(age, breaks = c(20, 30, 40, 50)))] 

or dplyr

library(dplyr) df1 %>%     group_by(age_group = cut(age, breaks = c(20, 30, 40, 50))) %>%     summarise(total_amount = sum(amount_spent)) #     age_group total_amount #      <fctr>        <int> #1   (20,30]           30 #2   (30,40]           37 #3   (40,50]           32 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -