iskandarblue
iskandarblue

Reputation: 7526

Hourly time series in R

I have sample time data (below) in POSIXct format, but am unable to convert it to an hourly time series using ts().

> dat
 [1] "2017-09-25 07:34:53 EDT" "2017-09-25 07:56:43 EDT" "2017-09-25 08:33:40 EDT"
 [4] "2017-09-25 08:34:24 EDT" "2017-09-25 08:43:33 EDT" "2017-09-25 09:34:53 EDT"
 [7] "2017-09-25 09:36:07 EDT" "2017-09-25 09:40:50 EDT" "2017-09-25 10:19:12 EDT"
[10] "2017-09-25 10:22:03 EDT" "2017-09-25 10:27:01 EDT" "2017-09-25 10:35:01 EDT"
[13] "2017-09-25 11:09:54 EDT" "2017-09-25 11:17:37 EDT" "2017-09-25 11:18:25 EDT"
[16] "2017-09-25 11:59:50 EDT" "2017-09-25 12:38:06 EDT" "2017-09-25 12:41:41 EDT"
[19] "2017-09-25 13:02:44 EDT" "2017-09-25 13:17:23 EDT" "2017-09-25 13:30:40 EDT"
[22] "2017-09-25 13:42:03 EDT" "2017-09-25 13:56:27 EDT" "2017-09-25 14:23:59 EDT"
[25] "2017-09-25 15:42:51 EDT"

My goal is to subsequently display this hourly time-series with dygraph(). In the example below, I have a time series by day produced with the following code:

trips <- as.data.frame(matrix(ncol=1, nrow=30))
colnames(trips) <- c("count")
trips$count <-  floor(runif(30, min=50, max=101))
z <- zoo(trips, seq(from = as.Date("2017-09-01"), to = as.Date("2017-09-30"), by = 1))

z <- as.ts(z)

dygraph(z, main = "Daily Trips") 

enter image description here

How can I properly convert POSIXct to an hourly time series knowing the difference in hours between first and end records ?

Here is the sample data:

> dput(dat)
structure(c(1506339293, 1506340603, 1506342820, 1506342864, 1506343413, 
1506346493, 1506346567, 1506346850, 1506349152, 1506349323, 1506349621, 
1506350101, 1506352194, 1506352657, 1506352705, 1506355190, 1506357486, 
1506357701, 1506358964, 1506359843, 1506360640, 1506361323, 1506362187, 
1506363839, 1506368571), class = c("POSIXct", "POSIXt"), tzone = "")

Upvotes: 0

Views: 969

Answers (1)

erasmortg
erasmortg

Reputation: 3278

Maybe something like this:

z = ts(dat, start =1, end =8, frequency = 1)
class(z) <- c("POSIXct", "POSIXt")
#[1] "2017-09-25 13:34:53 GMT" "2017-09-25 13:56:43 GMT" "2017-09-25 14:33:40 GMT" "2017-09-25 14:34:24 GMT" "2017-09-25 14:43:33 GMT" "2017-09-25 15:34:53 GMT" "2017-09-25 15:36:07 GMT" "2017-09-25 15:40:50 GMT"

Another try:

seq(from =dat[1], to = dat[length(dat)], by ='hour')
#[1] "2017-09-25 13:34:53 GMT" "2017-09-25 14:34:53 GMT" "2017-09-25 15:34:53 GMT" "2017-09-25 16:34:53 GMT" "2017-09-25 17:34:53 GMT" "2017-09-25 18:34:53 GMT" "2017-09-25 19:34:53 GMT" "2017-09-25 20:34:53 GMT" "2017-09-25 21:34:53 GMT"

The second has a length of 9, one per unique hour in the original dat

Third option:

library(lubridate)
library(data.table)

df = data.frame(timestamps = dat, bases = floor_date(dat, 'hour'))

setDT(df)
graph = df[,.N, by = bases]
dygraph(graph)

This will give the following dygraph: enter image description here

Upvotes: 1

Related Questions