Last active
April 19, 2018 18:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, that's useful!