[R] Subtracting timeseries objects

Gabor Grothendieck ggrothendieck at gmail.com
Tue Nov 15 21:33:21 CET 2005


On 11/15/05, tom wright <tom at maladmin.com> wrote:
> Sorry to keep posting but I want to do this right and I'm hoping for
> some pointers
> I now have two time series objects which I need to subtract.
> Unfortunatly the two series dont have the same sample rates.
> When I try to subtract them
>
> avgSub<-avg1-avg2
>
> The time series object is clever enough to object.
> So I guess I need to write a function for subtraction of the time series
> objects which will need to interpolate the samples to the same sampling
> time (this linear interpolation should be ok here)

Convert it to zoo, perform the calculation and convert it back:

   library(zoo)
   z <- na.approx(merge(as.zoo(ts1), as.zoo(ts2)))
   as.ts(z[,1] - z[,2])

> I would like to make this function the default one to be used when a ts
> subtractin is attempted. Unfortunatly I dont really have much idea where
> to start with this. If someone could point me in the direction of some
> good reading I'll be grateful.

Its not a good idea to change the definition of
subtraction in ts but you could create a subclass
of ts and then define your own subtraction method
for that.

"-.myts" <- function(x, y) {
   z <- na.approx(merge(as.zoo(ts1), as.zoo(ts2)))
   myts <- as.ts(z[,1] - z[,2])
   class(myts) <- c("myts", class(myts))
   myts
}

class(ts1) <- c("myts", class(ts1))
class(ts2) <- c("myts", class(ts2))
ts1 - ts2




More information about the R-help mailing list