Underwood
Underwood

Reputation: 260

Time Series subtraction in R

I want to compute RSS but how can I subtract these 2 Time Series?

> hw.pred$mean
Time Series:
Start = c(31, 1) 
End = c(32, 7) 
Frequency = 24 
# time series 1
ts1 <- c(12.84671, 12.65456, 12.54750, 12.27567, 12.03156, 11.72961, 
  11.85315, 12.62616, 13.93351, 15.48823, 16.71980, 17.59585, 
  18.37028, 18.92002, 18.98509, 18.65031, 18.43188, 17.87784, 
  17.30107, 16.51674, 15.89563, 15.22804, 14.63024, 13.71845, 
  12.77233, 12.58274, 12.47771, 12.20874, 11.96726, 11.66817, 
  11.79229)
> temp.ts2
Time Series:
Start = c(18, 1) 
End = c(19, 7) 
Frequency = 24 
# time series 2
ts2 <- c(12.316675, 11.766675, 11.000000, 10.866675, 10.000000, 9.766668, 
9.616658, 12.950000, 14.966650, 16.800000, 18.866675, 20.000000, 
20.366675, 20.800000, 20.299975, 19.816675, 19.000000, 18.166675, 
17.700000, 17.216675, 16.116675, 16.000000, 15.166675, 14.833325, 
13.116675, 12.850000, 11.216675, NA, NA, 11.000000, 11.183325)

Upvotes: 1

Views: 385

Answers (1)

TarJae
TarJae

Reputation: 78937

You can use zoo package. First we create a subclass of ts and then define the subtraction method.

library(zoo)
myts1 <- ts(ts1, start=c(31, 1), end=c(32, 7), frequency=24)
myts2 <- ts(ts2, start=c(18, 1), end=c(19, 7), frequency=24)

"-.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))

myts3 <- ts1 - ts2
myts3

# output:
Time Series:
Start = 1 
End = 31 
Frequency = 1 
 [1]  0.530035  0.887885  1.547500  1.408995  2.031560  1.962942  2.236492 -0.323840 -1.033140 -1.311770 -2.146875 -2.404150
[13] -1.996395 -1.879980 -1.314885 -1.166365 -0.568120 -0.288835 -0.398930 -0.699935 -0.221045 -0.771960 -0.536435 -1.114875
[25] -0.344345 -0.267260  1.261035  1.064290  0.895035  0.668170  0.608965

data:

# time series 1
ts1 <- c(12.84671, 12.65456, 12.54750, 12.27567, 12.03156, 11.72961, 
  11.85315, 12.62616, 13.93351, 15.48823, 16.71980, 17.59585, 
  18.37028, 18.92002, 18.98509, 18.65031, 18.43188, 17.87784, 
  17.30107, 16.51674, 15.89563, 15.22804, 14.63024, 13.71845, 
  12.77233, 12.58274, 12.47771, 12.20874, 11.96726, 11.66817, 
  11.79229)


# time series 2
ts2 <- c(12.316675, 11.766675, 11.000000, 10.866675, 10.000000, 9.766668, 
9.616658, 12.950000, 14.966650, 16.800000, 18.866675, 20.000000, 
20.366675, 20.800000, 20.299975, 19.816675, 19.000000, 18.166675, 
17.700000, 17.216675, 16.116675, 16.000000, 15.166675, 14.833325, 
13.116675, 12.850000, 11.216675, NA, NA, 11.000000, 11.183325)

Upvotes: 1

Related Questions