Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Merge Time Series in R

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will discuss how to merge time series in the R Programming language.

Time Series in R is used to analyze the behaviors of an object over a period of time. In R Language, it can be done using the ts() function. Time series takes the data vector and each data is connected with timestamp value. The ts() function is used to forecast the behavior of an asset in business for a period of time.

Syntax: ts(data, start, end, frequency)

Parameters:

  • data: determines the data vector used.
  • start: determines the date stamp of the first observation.
  • end: determines the date stamp of the last observation.
  • frequency: determines the number of observations per unit time.

Example: Created time series using vector data using the ts() function

R




# create data vector
x <- c(1,2,3,4,5,6,7,8,9,10,
       11,12,13,14,15,16,17)
  
# creating time series object
# from date October, 2021
ts(x, c(2021,10),frequency=12 )

Output:

       Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2021                                       1   2   3
2022   4   5   6   7   8   9  10  11  12  13  14  15
2023  16  17 

Merge time series in R

To merge two time series in R, we use the ts() function but as parameter data, we pass a vector that contains all the time series to be merged.

Syntax: ts( c(ts_1, ts_2), start = start(ts_1),  frequency = frequency(ts_1) )

Example:

Here, we have created two-time series and merged them using the above syntax.

R




# create data vectors
x <- c(1,2,3,4,5,6,7,8,9,10,11,12)
y <- c(13,14,15,16,17,18,19,20,21,22,23,24)
  
# creating time series objects
ts_1 <- ts(x, c(2021,10),frequency=12 )
ts_2 <- ts(y, c(2022,10),frequency=12 )
  
# merge time series
merged_ts <- ts(c(ts_1, ts_2),               
   start = start(ts_1),
   frequency = frequency(ts_1))
  
# print merged time series
merged_ts

Output:

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2021                                       1   2   3
2022   4   5   6   7   8   9  10  11  12  13  14  15
2023  16  17  18  19  20  21  22  23  24  

My Personal Notes arrow_drop_up
Last Updated : 05 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials