Home > Software design >  R ts object format changes after train test splitting
R ts object format changes after train test splitting

Time:10-26

I have a ts object

TorontoTempts <- ts(tempToronto$AvgTemperature, start=c(2015, 1), frequency=12)

I want to split it to train and test using subset:

train.ts <- subset(TorontoTempts, start = 1, end = 176)
testing.ts <- subset(TorontoTempts, start = 177, end = 200)

I did get the following error:

argument "subset" is missing, with no default

If works with the following code:

train.ts <- subset(TorontoTempts, subset=TRUE, start = 1, end = 176)
testing.ts <- subset(TorontoTempts,subset=TRUE, start = 177, end = 200)

However, when I want to pass it to tslm:

regModel <- tslm(train.ts ~ trend   season)

I receive the following error:

Error in tslm(train.ts ~ trend   season) : Not time series data, use lm()

CodePudding user response:

subset has no ts method in base R. You can

1) Use the forecast package which does have a subset.ts method:

tt <- ts(11:21, freq = 4) # test data

library(forecast)
subset(tt, start = 1, end = 3)

2) Convert to zoo and then use head, tail or subscripting and convert back.

library(zoo)

as.ts(head(as.zoo(tt), 3))

as.ts(as.zoo(tt)[1:3])

CodePudding user response:

For subsetting time series, R has the function window:

train.ts <- window(TorontoTempts, c(2015,1), c(2018,4))

  • Related