Skip to content

Instantly share code, notes, and snippets.

@alexland
Last active April 19, 2018 18:08
Show Gist options
  • Save alexland/af97f835785fee30d6b6 to your computer and use it in GitHub Desktop.
Save alexland/af97f835785fee30d6b6 to your computer and use it in GitHub Desktop.
convert an irregular time series to one with equal intervals between data points.
require(zoo)
require(xts)
#---------------------- mock an irregular (non-uniform interval) time series -----------------------#
start <- Sys.time() - (20 * 60 * 60)
end <- Sys.time()
# create the time series index
idx_ts = seq.POSIXt(start, end, by='hours')
idx_b = sample(c(TRUE, FALSE), length(idx_ts), replace=TRUE)
idx_ts = idx_ts[idx_b]
# create data associated with the index
x = runif(length(idx_ts))
ts1 = xts(x, idx_ts)
#------------------------- create an 'empty' time series (index only) --------------------------#
idx_ts = sort(idx_ts)
start = first(idx_ts)
end = last(idx_ts)
idx_grid = xts(order.by=seq.POSIXt(start, end, by='hours'))
> nhours(idx_grid)
[1] 19
> nhours(ts1)
[1] 9
#----------------------- merge the original time series & the empty grid -------------------------#
ts1_reg <- merge(ts1, idx_grid, all=TRUE)
# to replace the missing values with the last value just before the NA ('last obervation carried forward')
ts1_reg <- na.locf(merge(ts1, idx_grid, all=TRUE)
# couple of assertions
stopifnot( length(ts1_reg) == length(index(idx_grid) )
stopifnot( length(ts1_reg) > length(ts1) )
@pierrecattin
Copy link

Thanks, that's useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment