r - 如何使用 period.apply 将 R 中的 xts 对象列表转换为每周平均值?
问题描述
我正在尝试根据已拆分为列表的 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 对象的每周平均值。任何帮助将不胜感激。
解决方案
split
先转换成比较容易xts
。period.apply
您也可以使用apply.weekly
. 下面的代码显示了如何在单独的步骤中完成所有操作。我没有使用 tidyverse 之类的任何函数map
,但只会使用它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
。这就是它返回错误的原因,因为无法将列表强制为端点向量。
推荐阅读
- ios - 如何从另一个控制器打开嵌入式 segue 控制器?
- java - “如何在 android webview 中修复 recaptcha 询问 10-20 次”
- excel - Excel中的过滤时间
- node.js - MissingSchemaError MongoDB
- sorting - syncsort 将 pd 精确转换为 zdf
- python - 从第一个 Combobox 获取值并更改第二个 Combobox 的值
- html - 无法在 Chrome 中将 flexbox 子项高度设置为 100%
- c# - 具有复杂项目层次结构的 .NET DataContract 序列化程序中的高递归深度问题
- c# - 如何在我的表单中更改所有面板的背景色
- python - 比较两个文件中的 x,y,z 坐标