I am sure this is straight forward but I just cant seem to get it to work. I have a data frame that represents daily totals. I simply want to sum the totals by week, retai
A solution with the lubridate library:
library(lubridate)
Lines <- "date,amt
2009-04-01,45
2009-04-02,150
2009-04-03,165
2009-04-13,165
2009-04-14,45
2009-04-15,45
2009-05-15,45"
df <- read.csv(textConnection(Lines))
If you don't need 0 for missing weeks it's simple:
weeks <- week(df$date)
sums <- tapply(df$amt, weeks, sum)
# 14 15 16 20
#360 210 45 45
To put zeros for missing weeks:
span <- min(weeks):max(weeks)
out <- array(0, dim = length(span), dimnames = list(span))
out[dimnames(sums)[[1]]] <- sums
# 14 15 16 17 18 19 20
#360 210 45 0 0 0 45