【发布时间】:2017-04-22 00:45:36
【问题描述】:
如何使用比x 引用的因素更多的因素列表快速有效地拆分和合并xts 对象x?
这个简单的例子不会产生完整的因子列表(用零填充)。
a = cbind(value = runif(2), group = c(1,3))
x = xts(a, Sys.Date() + 1:nrow(a))
do.call(merge, c(split(x$value, x$group), fill = 0))
value.1 value.3
2016-12-08 0.3403723 0.0000000
2016-12-09 0.0000000 0.5247683
我的解决方法是附加与所有组关联的虚拟值,然后拆分和合并,然后像中一样删除虚拟值
all.groups = 1:5
x.all.groups = xts(cbind(value = 0, f = all.groups), Sys.Date()-1:length(all.groups))
x = rbind(x,x.all.groups)
as.xts(do.call(merge, c(split(x$value, x$group), fill = 0)))[!(index(x) %in% index(x.all.groups)),]
value.1 value.2 value.3 value.4 value.5
2016-12-08 0.3455855 0 0.00000 0 0
2016-12-09 0.0000000 0 0.16545 0 0
另一种解决方法是在操作split 和merge 之间附加缺失组的列表。
但是,这些解决方案似乎过于庞大。有什么建议?
有没有更好的方法来利用split(或其他一些函数)及其参数?
【问题讨论】: