【问题标题】:Extract previous day value from a time-series object in R从 R 中的时间序列对象中提取前一天的值
【发布时间】:2016-07-04 18:47:36
【问题描述】:

我有 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 索引提取这些类型的值?

【问题讨论】:

  • lag(xts_object, 24*6) 为您提供前一天,lag (xts_object, 48*6) 为您提供 prevday2 等。这假设您忽略了夏令时。
  • lag(xts_object, 1) 为您提供前一个瞬间。
  • 否,lag() 返回整个对象,其中一些观察值具有指定的na。我需要与特定的先前时间戳相对应的值。
  • 对不起,我不明白你在这里做什么。因为如果您正确选择滞后,如果您忽略 DLS 效应,滞后对象确实可以让您在同一时间范围内准确观察到前一天。

标签: r time-series xts


【解决方案1】:

在挣扎了一整天后,我想出了一种方法来填充剩余的三列。方法是:

  1. 提取/读取当前观察的索引
  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
       }  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2019-11-28
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多