问题描述
我正在尝试使用 R 为从 2015 年 2 月 24 日开始到 2015 年 4 月 13 日结束的每日时间序列创建一个 ts 对象.我已经为每日数据设置了频率 = 7,但我找不到将确切日期作为开始参数的方法.
I am trying to create a ts object using R for a daily time series that starts on 24.02.2015 and ends on 13.04.2015. I have put the frequency=7 for daily data but I cannot find a way to put the exact date as start argument.
推荐答案
我认为这就是你想要的,使用 'lubridate' 中的 decimal_date()
函数来获得正确的开始时间每日系列并假设您要索引为 ts 的值向量称为 x 并且具有适当的长度:
I think this is what you want, using the decimal_date()
function from 'lubridate' to get the proper start time for a daily series and assuming that the vector of values you want to index as a ts is called x and is of the proper length:
library(lubridate)
df <- ts(x, start = decimal_date(as.Date("2015-02-24")), frequency = 365)
如果我使用 rnorm()
生成适当长度的 x ,结果如下所示:
Here's what that looks like if I use rnorm()
to generate an x of the proper length:
> df
Time Series:
Start = c(2015, 55)
End = c(2015, 103)
Frequency = 365
[1] 0.4284579 1.9384426 0.1242242 -2.4002789 -0.4064669 0.6945274 -0.5172909 0.4772347 0.8758635 -1.7233406 0.5929249 1.5662611 1.0692173 -0.1354226
[15] 1.1404375 0.7714662 -0.2871663 -5.2720038 -1.7353146 -0.7053329 1.0206803 1.7170262 -0.3469172 0.2594851 2.0371700 -2.1549066 -0.6639050 -0.4912258
[29] -0.3849884 -3.0448583 -1.3317834 1.6173705 0.7176759 -0.8646802 -1.7697016 1.1114061 0.6941131 -0.1942612 -0.1836107 -0.5850649 -1.7449090 -3.3646555
[43] -0.4341833 1.9721407 1.4995265 1.7168002 1.8617295 -3.4578959 1.1639413
请注意,对于每日索引,您需要频率 = 365,而不是 7,这表示每周索引.
Note that for daily indexing, you want frequency = 365, not 7, which denotes weekly indexing.
如果您想要一个可以在动物园"中使用的日期向量,可以这样做:
If you want a vector of dates that you can use in 'zoo' instead, this does it:
seq(from = as.Date("2015-02-24"), to = as.Date("2015-04-13"), by = 1)
所以你会像这样创建一个动物园对象:
So you would create a zoo object like this:
zoo(x, seq(from = as.Date("2015-02-24"), to = as.Date("2015-04-13"), by = 1))
这篇关于如何从特定日期开始创建每日时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!