# [R] align() function missing in R ?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jul 2 06:20:02 CEST 2007

On 6/29/07, Markus Loecher <markus at insightfromdata.com> wrote:
> Thank you for your responses, I should have given an example of the
> functionality I am looking for, here are three typical scenarios that
> I deal with a lot in my work:
>
> - a regular timeseries with lots of missing values that I want to
> convert to the corresponding regular time series with mssing values
> replaced by NAs, e.g.:
>         x = timeSeries(c(0.5,0.2,0.3,0.4,0.3,0.2,0.3), pos =
> c(1,2,5,8,9,12,14));
>         x.align = align(x, pos = 1:14, method = "NA");
> - a regular timeseries at a coarse scale which I want to linearly
> interpolate to a finer time scale:
>         x = ts(1:10, frequency = 4);
>         x.align = align(x, frequency = 8, method = "interp")
> - an irregular timeseries which I want to linearly interpolate to a
> regular time grid:
>         x = timeSeries(c(0.5,0.2,0.3,0.4,0.3,0.2,0.3), pos =
> c(1,2.5,3.2,4.1,5.7,6.5,7.3));
>         x.align = align(x, pos = 1:7, method = "interp");
>
> I am wondering how to easily code such a function using only window,
> ts.union and ts.intersect.

Here it is using zoo series:

library(zoo)
x <- c(0.5, 0.2, 0.3, 0.4, 0.3, 0.2, 0.3)

x1 <- zoo(x, c(1, 2, 5, 8, 9, 12, 14))
as.zoo(as.ts(x1))

x2 <- zooreg(1:10, frequency = 4)
frequency(x2) <- 8
x2

x3 <- zoo(x,  c(1, 2.5, 3.2, 4.1, 5.7, 6.5, 7.3))
tt <- 1:7
zoo(approx(time(x3), x3, tt)\$y, tt)
# or
tt <- as.numeric(1:7) # can omit if warning in next line ok
window(na.approx(cbind(x3, zoo(, tt))), tt)

For more on zoo:

library(zoo)
vignette("zoo")