I have the following data:
set.seed(123)
timeseq <- as.Date(Sys.time() + cumsum(runif(1000)*86400))
data <- rnorm(1000)
df <- data.frame(timeseq,data)
I wanted to know if anyone has any methods on how to aggregate data
by week. What I am attempting to do is plot a time series ggplot, so even better if I can skip this step and have ggplot handle this. Been stuck on this all day.
Another way to manually aggregate by week using dplyr.
library(dplyr)
df$weeks <- cut(df[,"timeseq"], breaks="week")
agg <- df %>% group_by(weeks) %>% summarise(agg=sum(data))
ggplot(agg, aes(as.Date(weeks), agg)) + geom_point() + scale_x_date() +
ylab("Aggregated by Week") + xlab("Week") + geom_line()
You can also aggregate a date aesthetic with the scale_x_date()
function's breaks
argument.
ggplot(df, aes(x = timeseq, y = data)) +
stat_summary(fun.y = sum, geom = "line") +
scale_x_date(labels = date_format("%Y-%m-%d"),
breaks = "1 week")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With