Create Time Series in R: Complete Guide
In R language, you can use the ts() function to create a time series. The syntax of the ts() function is as follows:
ts(data, start, end, frequency)
In this case, data is a vector or matrix representing the data of a time series; start denotes the beginning time of the time series; end denotes the end time of the time series; frequency represents the frequency of the time series.
Here is an example of creating a time series:
# 创建一个包含每月销售额的时间序列
sales <- c(120, 150, 180, 140, 160, 200, 180, 190, 210, 220, 230, 250)
start_date <- as.Date("2020-01-01")
end_date <- as.Date("2020-12-01")
frequency <- 12
# 使用ts()函数创建时间序列
ts_sales <- ts(sales, start = c(year(start_date), month(start_date)), end = c(year(end_date), month(end_date)), frequency = frequency)
In the above code, a vector called sales containing monthly sales amounts is first defined, and then the starting and ending times are converted to date format using the as.Date() function. Next, a time series named ts_sales is created using the ts() function, with a start time of January 2020, end time of December 2020, and a frequency of 12, representing 12 months per year.