Reputation: 143
I've been trying to merge two ts objects, the second one starts exactly one period after the next one. For example, take the following two time series
ts1<-ts(c(1:12),star=c(2014,1),freq=12)
ts2<-ts(c(13:24),star=c(2015,1),freq=12)
As you can see, both of them match perfectly in order to make a single ts out of this two ts objects. I thought the logical answer would be the rbind() function. But it makes a matrix out of them, as follows...
> rbind(ts1,ts2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
ts1 1 2 3 4 5 6 7 8 9 10 11 12
ts2 13 14 15 16 17 18 19 20 21 22 23 24
I've tried without success other functions like merge,cbind. Using c() I've managed to get one only timeseries, the main problema is that I lose structure attributes of the original timeseries, this is bad because I'm trying to use the function forecast with the new ts but it gives me this:
Error: variables ... were specified with different types from the fit
I would be happy just with being able to add additional observations to a time series. Something like adding the value 13 to ts1 for January,2015 but I haven´t found how to do this either.
I think is funny because I see this as a perfectly natural thing to ask for to a ts object, but I haven´t found any other question that helps me out here. Well let´s hope this is not a too silly question.
Upvotes: 13
Views: 21166
Reputation: 59
This worked for me
ts.union(ts1, ts2)
ts1 ts2
Jan 2014 1 NA
Feb 2014 2 NA
Mar 2014 3 NA
Apr 2014 4 NA
May 2014 5 NA
Jun 2014 6 NA
Jul 2014 7 NA
Aug 2014 8 NA
Sep 2014 9 NA
Oct 2014 10 NA
Nov 2014 11 NA
Dec 2014 12 NA
Jan 2015 NA 13
Feb 2015 NA 14
Mar 2015 NA 15
Apr 2015 NA 16
May 2015 NA 17
Jun 2015 NA 18
Jul 2015 NA 19
Aug 2015 NA 20
Sep 2015 NA 21
Oct 2015 NA 22
Nov 2015 NA 23
Dec 2015 NA 24
Upvotes: 5
Reputation: 36
You could use the xts package which will take care of details for you (for instance even if the series have a gap)
library(xts)
ts1<-as.xts(ts(c(1:12),star=c(2014,1),freq=12))
ts2<-as.xts(ts(c(13:24),star=c(2015,1),freq=12))
str(ts3 <- c(ts1, ts2))
# An ‘xts’ object on Jan 2014/Dec 2015 containing:
# Data: int [1:24, 1] 1 2 3 4 5 6 7 8 9 10 ...
# Indexed by objects of class: [yearmon] TZ:
# xts Attributes:
# NULL
Cheers, Peter
Upvotes: 2
Reputation: 10223
I think you're looking for something like
comb <- ts.union(ts1, ts2)
pmin(comb[,1], comb[,2], na.rm = TRUE)
# Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
#2014 1 2 3 4 5 6 7 8 9 10 11 12
#2015 13 14 15 16 17 18 19 20 21 22 23 24
Upvotes: 8
Reputation: 263321
You need to reassign the attributes from the first series.
> ts(c(ts1,ts2), start=start(ts1), frequency=frequency(ts1))
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2014 1 2 3 4 5 6 7 8 9 10 11 12
2015 13 14 15 16 17 18 19 20 21 22 23 24
Upvotes: 10