Quantcast
Channel: Active questions tagged xts - Stack Overflow
Viewing all articles
Browse latest Browse all 57

How to aggregate a dataframe by week?

$
0
0

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         Mon2  2014-02-25     45        Tues3  2014-02-26     30         Wed4  2014-02-27     50       Thurs5  2014-02-28     50         Fri6  2014-03-01     20         Sat7  2014-03-02     35         Sun8  2014-03-03     50         Mon9  2014-03-04     35        Tues10 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?


Viewing all articles
Browse latest Browse all 57

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>