时间序列每周数据 [英] Time series weekly data
问题描述
我对 R 非常陌生,并尝试在将数据作为 csv 文件移入 R 之前在 excel 中操作我的数据.我想将 ts()
用于每周数据.你能做一些像年 1-12 月、1-4 周这样简单的事情吗?MWY.我在想,如果我将第 1-7 天用作第一周等等,那将是统一的,并且可以轻松实现我的目的,但我不知道如何编写它.使用这个网站和另一个教程我想出了这个:
I am very new to R and trying to manipulate my data in excel before moving it into R as a csv file. I would like to use ts()
for weekly data. Can you do something as simple as Month 1-12, week 1-4, year? MWY. I was thinking if I use day 1-7 as week one and so on that would be uniform and work easy for my purpose but I don't know how to write it. Using this site and another for a tutorial I came up with this:
myts <- ts(Time2012, start = c(8/3/2013,1), end = c(9/2/2013,4), frequency = 52)
有没有什么简单的方法可以表示我想计算周数的日期?
is there any easy way to denote the date to show I want to count weeks?
推荐答案
我会推荐一种稍微不同的工作流程,您可能会发现它具有更广泛的实用性:
i would recommend a slightly different workflow, one which you will likely find has broader utility:
> end = Sys.Date()
> start = end - 365
> class
> # create the index array comprised of date objects
> ndx = seq(start, end, by='weeks')
> class(ndx)
[1] "Date"
> length(ndx)
[1] 53
> # create a fake data array
> x = 1:length(ndx)
> mydata = sin(x/2)
> # import a time series library
> require(xts)
> # create the time series
> myts = xts(mydata, order.by=ndx)
> myts[1:5]
[,1]
2012-09-19 3.479426
2012-09-26 3.841471
2012-10-03 3.997495
2012-10-10 3.909297
2012-10-17 3.598472
> class(myts)
[1] "xts" "zoo"
> periodicity(myts)
Weekly periodicity from 2012-09-19 to 2013-09-18
或者,如果您的数据不是按周计算的,那么您可以创建一个具有更高分辨率(例如,天)的时间序列,然后将其汇总到周:
Alternatively, if your data is not by week, then you can create a time series having a higher resolution (eg, days) then roll it up to weeks:
> ndx = seq(start, end, by='days')
> x = 1:length(ndx)
> mydata = sin(x/2) + 3
> myts = xts(mydata, order.by=ndx)
> myts[1:5]
[,1]
2012-09-19 3.479426
2012-09-20 3.841471
2012-09-21 3.997495
2012-09-22 3.909297
2012-09-23 3.598472
> periodicity(myts)
Daily periodicity from 2012-09-19 to 2013-09-19
> # now roll-up this daily series to weeks
> require(xts)
> # first create the endpoints
> np = endpoints(myts, on='weeks')
> myts_weeks = period.apply(x=myts, INDEX=np, FUN=sum, na.rm=TRUE)
> myts_weeks[1:5]
[,1]
2012-09-23 18.82616
2012-09-30 17.11212
2012-10-07 24.93492
2012-10-14 17.51811
2012-10-21 23.58635
> periodicity(myts_weeks)
Weekly periodicity from 2012-09-23 to 2013-09-19
这篇关于时间序列每周数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!