Skip to content
Prev 15132 / 15274 Next

xts: Transfer/expand values to higher periodicity

On Fri, Aug 11, 2023 at 3:22?PM Mike <mike9 at posteo.nl> wrote:
Thanks for the reproducible example. It makes it a lot easier to help!

Note that the index for x.daily is POSIXct even though it's daily
data. You need to make sure it's Date in your case or you'll have
timezone issues with this approach.

x.daily <- as.xts(sample_matrix)
# convert to Date index
index(x.daily) <- as.Date(index(x.daily))

Now you can merge your daily series with the weekly series and use
na.locf() to fill the gaps.

x.daily.new <- merge(x.daily, x.weekly$M, fill = na.locf)

The first 3 observations are NA because there's no observation for the
first day of the week at the beginning of the series. You can fill
those values backward by setting fromLast = TRUE)

x.daily.new <- na.locf(x.daily.new, fromLast = TRUE)
x.daily.new
##                Open     High      Low    Close        M
## 2007-01-02 50.03978 50.11778 49.95041 50.11778 50.18615
## 2007-01-03 50.23050 50.42188 50.23050 50.39767 50.18615
## 2007-01-04 50.42096 50.42096 50.26414 50.33236 50.18615
## 2007-01-05 50.37347 50.37347 50.22103 50.33459 50.18615
## 2007-01-08 50.03555 50.10363 49.96971 49.98806 50.18615
## 2007-01-09 49.99489 49.99489 49.80454 49.91333 50.18615
## 2007-01-10 49.91228 50.13053 49.91228 49.97246 50.18615
## 2007-01-11 49.88529 50.23910 49.88529 50.23910 50.18615
## 2007-01-12 50.21258 50.35980 50.17176 50.28519 50.08217
## 2007-01-15 50.61724 50.68583 50.47359 50.48912 50.08217
##        ...
## 2007-06-18 47.43470 47.56336 47.36424 47.36424 47.33332
## 2007-06-19 47.46055 47.73353 47.46055 47.67220 47.33332
## 2007-06-20 47.71126 47.81759 47.66843 47.66843 47.33332
## 2007-06-21 47.71012 47.71012 47.61106 47.62921 47.33332
## 2007-06-22 47.56849 47.59266 47.32549 47.32549 47.57154
## 2007-06-25 47.20471 47.42772 47.13405 47.42772 47.57154
## 2007-06-26 47.44300 47.61611 47.44300 47.61611 47.57154
## 2007-06-27 47.62323 47.71673 47.60015 47.62769 47.57154
## 2007-06-28 47.67604 47.70460 47.57241 47.60716 47.57154
## 2007-06-29 47.63629 47.77563 47.61733 47.66471 47.45484