Reputation: 55
I have a data frame that consists of hourly time series, but my problem is that the format is %Y/%m/%d, meaning that each date repeats 24 times. I can't seem to figure out how to add the hour property to my date object. This is an example:
Date
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
1997/01/01
I tried adding +3600 to each row but I only got:
Date
1997-01-01 01:00:00
1997-01-01 01:00:00
1997-01-01 01:00:00
1997-01-01 01:00:00
1997-01-01 01:00:00
I would like to end up with something like this in each row:
1997/01/01 00:00
1997/01/01 01:00
1997/01/01 02:00
1997/01/01 03:00
...
So I could aggregate the data from hourly to daily. I looked into previous posts but didn't have any luck. Any hint of help would be very appreciated. Many thanks.
Upvotes: 0
Views: 306
Reputation: 887391
Another option with anytime
library(anytime)
df$Date <- anytime(df$Date) + (3600 * (0:23))
Upvotes: 0
Reputation: 389065
In base R you can use recycling technique to add hours.
df$Date <- as.POSIXct(df$Date) + 0:23 * 3600
Upvotes: 0
Reputation: 2364
Try this:
library(lubridate)
df$Date + hours(((1:length(df$Date) -1 ) %% 24 + 1))
It will work if your Date
column is already formatted as date (use ymd()
or as.Date()
)
Upvotes: 1