You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中ts()函数start参数原理及小时时间序列创建疑问

Understanding ts() for Hourly Time Series & Fixing Your Date Issue

Let's tackle your two questions one by one, with concrete fixes for your code.

1. How does the start parameter in ts() work?

The start argument in ts() takes a vector c(year, period), where period is defined entirely relative to the frequency you set:

  • frequency represents the number of observations per full cycle (e.g., 12 for monthly data, 365 for daily, 8760 for hourly data across a non-leap year)
  • The period value marks the exact position of your first observation within that cycle.

For example:

  • If frequency=12 (monthly data), start=c(2017, 10) means the 10th observation of 2017—aka October.
  • If frequency=8760 (hourly data for a non-leap year), start=c(2017, 6768) means the 6768th hour of 2017.

Your mistake was passing the day of year (282) as the period when frequency=8760. Since 282 hours into 2017 equals ~11.75 days, that’s why you ended up with 2017-01-12 instead of your intended start date.

2. Can you create an hourly time series with ts() for use with tslm()?

Absolutely! You just need to correctly calculate the start period and set the right frequency. Here's how to fix your code:

Step 1: Calculate the correct starting hour position in the year

Your first observation is 2017-10-09 00:00:00, which is the 282nd day of 2017. Convert this to its hour position in the year:

start_day_of_year <- as.numeric(format(df$interval[1], "%j"))
start_hour_in_year <- start_day_of_year * 24 + as.numeric(format(df$interval[1], "%H"))
# This gives 282*24 + 0 = 6768

Step 2: Create the ts object with correct parameters

Use frequency=8760 (total hours in a non-leap year; use 8784 if your data spans a leap year):

df.ts <- ts(
  data = df$total,
  start = c(2017, start_hour_in_year),
  frequency = 24 * 365  # 8760 hours per non-leap year
)

Step 3: Verify the start date

Check the starting date again with date_decimal() (from the lubridate package):

library(lubridate)
head(date_decimal(index(df.ts)), 1)
# Should return "2017-10-09 UTC" (with 00:00:00 depending on your locale)

Alternative: Focus on daily hourly seasonality

If you want to model daily hourly patterns instead of annual cycles, set frequency=24 and define start using a decimal date for the first day:

start_decimal_date <- decimal_date(df$interval[1])
df.ts_daily_season <- ts(
  data = df$total,
  start = c(start_decimal_date, 0),
  frequency = 24
)

This structure works perfectly with tslm() and makes it easier to analyze daily trends.


内容的提问来源于stack exchange,提问作者Elena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:42:05