Home > Enterprise >  How to do aggregate sum by time range in R?
How to do aggregate sum by time range in R?

Time:08-25

I have a dataframe as below:

**df**
Cust_name   time    freq
Andrew       0       4
Dillain      1       2
Alma         2       3
Andrew       1       4
Kiko         2       1
Sarah        2       8
Sarah        0       3

I want to calculate the sum of frequency by the time range provided for each cust_name. Example: If I select time range 0 to 2 for Andrew, it will give me sum of freq: 4 4= 8. And for Sarah, it will give me 8 3=11. I have tried it in the following ways just to get the time range, but do not know how to do the rest, as I am very new to R:

df[(df$time>=0 & df$time<=2),]

CodePudding user response:

You can do this with dplyr. To make your code reproducible, you should add the creation of your dataframe in your post. Copy and pasting everything is time consuming.

library(dplyr)
df <- data.frame(
  cust_name = c('Andrew', 'Dillain', 'Alma', 'Andrew', 'Kiko', 'Sarah', 'Sarah'),
  time = c(0,1,2,1,2,2,0),
  freq = c(4,2,3,4,1,8,3)
)

df %>%
  filter(time >=0, time <=2) %>%
  group_by(cust_name) %>%
  summarise(sum_freq = sum(freq))
  • Related