时间序列每周数据

时间:2013-09-19 18:57:40

标签: r time-series

我是R的新手并尝试在excel中操作我的数据,然后将其作为csv文件移到R中。我想将ts()用于每周数据。你可以做一些简单的事情,如第1-12个月,第1-4周,一年? MWY。我在想是否将第1-7天用作第一周等等,这将是统一的,并且对我的目的来说很容易,但我不知道如何写它。使用这个网站和另一个教程,我想出了这个:

myts <- ts(Time2012, start = c(8/3/2013,1), end = c(9/2/2013,4), frequency = 52)

有没有简单的方法来表示我希望计算数周的日期?

2 个答案:

答案 0 :(得分:1)

我会建议稍微不同的工作流程,您可能会发现它具有更广泛的实用性:

> 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 

或者,如果您的数据不是按周计算,那么您可以创建一个具有更高分辨率(例如天数)的时间序列,然后将其累计到几周:

> 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 

答案 1 :(得分:1)

创建一组年,月,周(月)的简单方法是使用lubridate

require(lubridate)

# Your starting date, plus 52 more dates at weekly intervals
xDates <- dmy("8/3/2013") + weeks(0:52)

# A data frame of the dates, the month of the year, and the week of the month
xYMW <- data.frame(date=(xDates), month=month(xDates), week=mday(xDates) %/% 7 + 1)
xYMW[1:5, ]
        date month week
1 2013-03-08     3    2
2 2013-03-15     3    3
3 2013-03-22     3    4
4 2013-03-29     3    5
5 2013-04-05     4    1