【问题标题】:How do I convert a list of xts objects in R to weekly averages using period.apply?如何使用 period.apply 将 R 中的 xts 对象列表转换为每周平均值?
【发布时间】:2019-06-26 03:02:51
【问题描述】:

我正在尝试根据已拆分为列表的 xts 对象创建每周平均值,但我不断收到错误消息:

Error in isOrdered(INDEX) : 
  (list) object cannot be coerced to type 'double'

我尝试过使用 period.apply 函数。

> str(rate_data)
'data.frame':   887079 obs. of  3 variables:
 $ LoadDate       : Date, format: "2018-03-05" "2018-02-21" "2018-02-07" ...
 $ laneid         : Factor w/ 6905 levels "  _FL_Van","  _PA_Van",..: 4629 
579 6538 5944 1213 1213 6029 5564 4287 5745 ...
 $ TruckPayPerMile: num  3.62 1.5 1.33 2.39 1.01 ...

> head(rate_data)
    LoadDate       laneid TruckPayPerMile
1 2018-03-05    OH_NY_Van          3.6231
2 2018-02-21 CA_AR_Reefer          1.5046
3 2018-02-07    WA_TX_Van          1.3333
4 2018-01-31    TX_MA_Van          2.3852
5 2018-01-29    FL_SC_Van          1.0149
6 2018-01-30    FL_SC_Van          1.0683


rate_data_xts <- xts(rate_data, rate_data[ ,-2], order.by = rate_data[ ,2])

lanes_xts <- split(rate_data_xts, rate_data_xts$laneid)

tx_ca_reefer <- lanes_xts[["TX_CA_Reefer"]]

head(tx_ca_reefer)

    > head(tx_ca_reefer)
           LoadDate   laneid       TruckPayPerMile
2018-01-28 2018-01-28 TX_CA_Reefer  1.6850        
2018-01-28 2018-01-28 TX_CA_Reefer  2.5128        
2018-01-29 2018-01-29 TX_CA_Reefer  2.4077        
2018-01-29 2018-01-29 TX_CA_Reefer  1.3610        
2018-01-29 2018-01-29 TX_CA_Reefer  1.8241        
2018-01-29 2018-01-29 TX_CA_Reefer  1.8703        
Warning message:
In zoo(rval, index(x)[i]) :
  some methods for “zoo” objects do not work if the index entries in 
‘order.by’ are not unique


end_points <- map(lanes_xts, endpoints, on = 'weeks')

lanes_weekly_xts <- period.apply(lanes_xts, INDEX = end_points, FUN = mean)

Error in isOrdered(INDEX) : 
      (list) object cannot be coerced to type 'double'

我想要的是列表中每个 xts 对象的每周平均值。任何帮助将不胜感激。

【问题讨论】:

  • 请创建一个可重现的示例。 rate_data 中包含什么?使用dput 将其添加到您的问题中。请参阅here 了解更多信息
  • 我已添加有关费率数据的信息。它是一个包含三个变量的数据框。包括一个日期列、一个因子列和一个数值列。

标签: r type-conversion time-series purrr


【解决方案1】:

split,再转换成xts比较容易。您也可以使用apply.weekly,而不是使用period.apply。下面的代码显示了如何在单独的步骤中完成所有操作。我没有使用map 之类的任何 tidyverse 函数,但只会使用 lapply 来达到预期的效果。

# split on laneid
lanes <- split(rate_data, rate_data$laneid)

# turn list in an list of xts objects without laneid in the matrix. 
# Otherwise the matrix will be a character matrix
lanes_xts <- lapply(lanes, function(x) xts(x[, 3], order.by = x[, 1]))

# use apply.weekly to apply a mean over the weeks.
lanes_weekly <- lapply(lanes_xts, apply.weekly, mean)

至于您遇到的错误。代码中的行 map(lanes_xts, endpoints, on = 'weeks') 返回端点列表。这不能在period.apply 中传递。这就是它返回错误的原因,因为无法将列表强制为端点向量。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2014-05-17
  • 2018-01-24
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2015-01-29
  • 2018-02-15
  • 2020-03-07
  • 2017-02-22
相关资源
最近更新 更多