创建一个唯一的周变量,不依赖于 R 中的日历

create an unique week variable NOT depending on the calendar in R

我有一个 每日 收入时间序列 df01-01-201415-06-2017 我想将每日收入数据汇总到每周收入数据并进行每周预测。在汇总收入之前,我需要 create a continuously week variable,这将 NOT 在新的一年开始时再次从第 1 周开始。由于 01-01-2014 不是星期一,所以我决定从 06-01-2014.

开始我的第一周

我的 df 现在看起来像这样

         date    year month     total 
 7    2014-01-06 2014     1 1857679.4   
 8    2014-01-07 2014     1 1735488.0    
 9    2014-01-08 2014     1 1477269.9    
 10   2014-01-09 2014     1 1329882.9    
 11   2014-01-10 2014     1 1195215.7  
 ...  
 709  2017-06-14 2017     6 1677476.9
 710  2017-06-15 2017     6 1533083.4

我想创建一个唯一的 week variable2014-01-06 开始直到我的数据集的最后一行(总共 1257 行),即 2017-06-15.

我写了一个循环:

   week = c()
   for (i in 1:179) {
   week = rep(i,7)
   print(week)
   }

但是,不会为每次迭代保存此循环的结果。当我输入 week 时,它只显示 179,179,179,179,179,179,179

问题出在哪里,在repeat循环后如何添加180, 180, 180, 180?

并且如果我将在 2017 年 6 月 15 日之后添加更多新数据,我如何根据我的行尾(日期)自动创建每周变量? (换句话说,通过这样做,我不需要计算我每天有多少观察并将其除以 7 加上其余日期成为周指数)

谢谢!

这个有用吗

library(lubridate)

#DATA
x = data.frame(date = seq.Date(from = ymd("2014-01-06"),
        to = ymd("2017-06-15"), length.out = 15))

#Add year and week for each date
x$week = year(x$date) + week(x$date)/100

#Convert the addition of year and week to factor and then to numeric
x$week_variable = as.numeric(as.factor(x$week))

#Another alternative
x$week_variable2 = floor(as.numeric(x$date - min(x$date))/7) + 1

x
#         date    week week_variable week_variable2
#1  2014-01-06 2014.01             1              1
#2  2014-04-05 2014.14             2             13
#3  2014-07-04 2014.27             3             26
#4  2014-10-02 2014.40             4             39
#5  2014-12-30 2014.52             5             52
#6  2015-03-30 2015.13             6             65
#7  2015-06-28 2015.26             7             77
#8  2015-09-26 2015.39             8             90
#9  2015-12-24 2015.52             9            103
#10 2016-03-23 2016.12            10            116
#11 2016-06-21 2016.25            11            129
#12 2016-09-18 2016.38            12            141
#13 2016-12-17 2016.51            13            154
#14 2017-03-17 2017.11            14            167
#15 2017-06-15 2017.24            15            180

答案如下:

 week = c()
 for (i in 1:184) {
    for (j in 1:7) {
            week[j+(i-1)*7] = i
    }
 }
 week = as.data.frame(week)

我创建了一个 week variable,从第 1 周到第 184 周(我的数据集结束)。对于每个周数,我重复 7 次,因为一周有 7 天。后来我将 week 变量分配给了我的 data frame.