Consider the following example
library(tidyverse)
library(lubridate)
time <- seq(from =ymd("2014-02-24"),to= ymd("2014-03-20"), by="days")
set.seed(123)
values <- sample(seq(from = 20, to = 50, by = 5), size = length(time), replace = TRUE)
df2 <- data_frame(time, values)
df2 <- df2 %>% mutate(day_of_week = wday(time, label = TRUE))
Source: local data frame [25 x 3]
time values day_of_week
<date> <dbl> <fctr>
1 2014-02-24 30 Mon
2 2014-02-25 45 Tues
3 2014-02-26 30 Wed
4 2014-02-27 50 Thurs
5 2014-02-28 50 Fri
6 2014-03-01 20 Sat
7 2014-03-02 35 Sun
8 2014-03-03 50 Mon
9 2014-03-04 35 Tues
10 2014-03-05 35 Wed
I would like to aggregate this dataframe by week.
That is, suppose I define a week as starting on Monday morning and ending on Sunday evening, which we will call a Monday to Monday
cycle. (importantly, I want to be able to choose other conventions, such as Friday to Friday for instance).
Then, I would simply like to count the mean of values
for each week.
For instance, in the example above, one would compute the average of values
between Monday February 24th to Sunday March 2nd, and so on.
How can I do that?
df2 %>% group_by(week = week(time)) %>% summarise(value = mean(values))
, or useisoweek
instead.week
function alistaire mentioned isn't exactly what you want, you can always sort the data and thencumsum(day_of_week == "Mon")
. The result will break if you don't have every day recorded, though.cut.Date
, which can do Sunday or Monday starts, if you like. Otherwise, you can add/subtract the appropriate number of days and use any of the options to shift the cut points.