从 R 中的时间序列对象中提取前一天的值

Extract previous day value from a time-series object in R

我有 10 分钟速率的时间序列(xts 格式)功耗数据为

                      power 
2015-08-01 00:00:00 101.22              
2015-08-01 00:10:00 122.941                
2015-08-01 00:20:00  67.596              
2015-08-01 00:30:00 184.180       

现在我想再添加 3 列:

  1. 第 2 列:"Prevday1" - 其中 "prevday1" 将同时包含前一天的功耗读数。也就是说,如果当前指数是 2015 年 8 月 5 日,1100 小时,那么 "prevday1" 应该包含前一天同一时间的消耗量(2015 年 8 月 4 日,1100 小时)
  2. 第 3 列:"Prevday2" - 其中 "prevday2" 将包含前一天同一时刻的功耗读数
  3. 第 4 列:"previnstant1" - 其中 "previnstant1" 将包含前一时刻的读数。在我的情况下,它会在 10 分钟前消耗电量

新的 xts 对象会像

                  power       prevday1     prevday2   previnstant1
2015-08-01 00:00:00 101.22       NA          NA          NA
2015-08-01 00:10:00 122.941      :            :           :
2015-08-01 00:20:00  67.596              
2015-08-01 00:30:00 184.180   
       :

现在的问题是我应该如何从历史 xts 对象中提取第 2、3 和 4 列的值。我从 .indexday 类型的函数开始,但无法获取值。 R 中是否有任何特定函数可以使用 xts 索引提取这些类型的值?

折腾了一整天,我想出了一个方法来填充剩下的三列。做法是:

  1. Extract/Read 当前观察指数
  2. 使用步骤1的指数计算前两天的指数
  3. 读取与步骤 2 的索引对应的值。这将分别填充第 2 列和第 3 列
  4. 找出时序数据的周期性,并利用这个周期性读取之前的值。这将填充列

代码是:

#x is a xts time series object containing columns as shown in question
 dates <- as.Date(index(x),tz="Asia/Kolkata") # timestamp in date format
 for(i in 0:200) # no. of observations
      {
      a <- x[i,1] # Current observation 
      prev_d1 <- as.Date(index(a), tz ="Asia/Kolkata")-1 # previous day
      prev_d2 <- as.Date(index(a), tz ="Asia/Kolkata")-2 # previous to previous day
      prev_value1 <- x[dates %in% prev_d1 & .indexhour(x) %in% .indexhour(a) & .indexmin(x) %in% .indexmin(a)]$power
      prev_value2 <- x[dates %in% prev_d2 & .indexhour(x) %in% .indexhour(a) & .indexmin(x) %in% .indexmin(a)]$power
      x[i,"prevday1"] <- if(length(prev_value1)!=0) prev_value1 else NA
      x[i,"prevday2"] <- if(length(prev_value2)!=0) prev_value2 else NA
      x[i,"previnstant1"] <- ifelse(length(x[index(a)-frequency]$power)!=0, x[index(a)-frequency]$power, NA)# frequency represents periodicity values in terms of seconds
       }