Take 7 Days Aveage Grouping

Hi,

I have a daily data that I want to take 7 days average grouping Type column.

My data:

Date Type Value
2020-01-01 A 2
2020-01-01 B 3
2020-01-02 A 5
2020-01-02 B 1
2020-01-03 A 2
2020-01-03 B 3
2020-01-04 A 4
2020-01-04 B 5

I want to sum group by last 7 days' value and divide by 7 (7 days average).

Example for 4 days:

Date Type Value Sum
2020-01-01 A 2 2
2020-01-01 B 3 3
2020-01-02 A 5 7
2020-01-02 B 1 8
2020-01-03 A 2 9
2020-01-03 B 3 7
2020-01-04 A 4 13
2020-01-04 B 5 12

Thank you.

Not sure what you really want. If you want to summarize by week and type, then create a new variable, "Week", and do

group_by(Type, Week) %>%
    summarize(Weekly_value=mean(Value)

For a running average, there are a number of ways to do it. I have tried several. My preferred is to use zoo.

#     Calculate a rolling average
window <- 7
  foo <- foo %>% 
    group_by(Type) %>% 
    mutate( avg = ~ zoo::rollapply(., window, 
                                   FUN=function(x) mean(x, na.rm=TRUE),
                                   fill=c(first(.), NA, last(.))))) %>% 
  ungroup()


1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.