Reputation: 2177
I'd like to create a time series chart in R that compares this year to last year. I'd like to use this year's dates as my x axis.
What is the function that, given a set of dates from 2 or more years, will make them all the same year?
Data example:
mydata <- data.frame(
date.col = as.Date(c('2014-05-23', '2014-05-24', '2014-05-25', '2015-05-23', '2015-05-24', '2015-05-25', '2016-05-23', '2016-05-24', '2016-05-25')),
value = c(10,23,15,13,26,17,22,30,19))
date.col value
1 2014-05-23 10
2 2014-05-24 23
3 2014-05-25 15
4 2015-05-23 13
5 2015-05-24 26
6 2015-05-25 17
7 2016-05-23 22
8 2016-05-24 30
9 2016-05-25 19
Expected output:
date.col value adj.date
1 2014-05-23 10 2016-05-23
2 2014-05-24 23 2016-05-24
3 2014-05-25 15 2016-05-25
4 2015-05-23 13 2016-05-23
5 2015-05-24 26 2016-05-24
6 2015-05-25 17 2016-05-25
7 2016-05-23 22 2016-05-23
8 2016-05-24 30 2016-05-24
9 2016-05-25 19 2016-05-25
Ideally, the function could fit easily into a dplyr chain:
mydata %>% normalize.dates(date.col, fit.to='2016') %>% ggplot(...)
Upvotes: 0
Views: 357
Reputation: 2177
This works well:
as.Date(format(date.col, '2016-%m-%d'))
Fit into a dplyr chain:
my.data %>% mutate(adj.date = as.Date(format(date.col, '2016-%m-%d'))) %>%
ggplot(aes(x=adj.date)) + ...
Useful for time series plots when all dates need to be normalized for year over year comparison:
mydata %>%
mutate(adj.date = as.Date(format(date.col, '2016-%m-%d'))) %>%
ggplot(aes(x=adj.date, y=value, color=as.factor(year(date.col)))) + geom_line()
Upvotes: 1