【发布时间】:2019-09-02 14:44:52
【问题描述】:
我正在寻找一种更简单的方法来使用另一个 xts 对象中的数据更新 xts 时间序列对象。应更新重叠时间段和维度的数据,应添加其他时间段,并应根据需要添加缺失的系列维度。目前我正在使用合并、子集和赋值的组合。有没有办法以更少的步骤做到这一点?
示例
具有一个共同维度 (y) 和两个共同时间段(2018 年第二季度和 2018 年第三季度)的两个 xts 时间序列对象。
library(xts)
t <- as.yearqtr(paste(2018, 1:4, sep = ":Q"), format = "%Y:Q%q")
short <- xts(
matrix(1, ncol = 2, nrow = 2, dimnames = list(NULL, c("x", "y"))),
order.by = t[2:3]
)
long <- xts(
matrix(0, ncol = 2, nrow = 4, dimnames = list(NULL, c("y", "z"))),
order.by = t
)
short
x y
2018 Q2 1 1
2018 Q3 1 1
long
y z
2018 Q1 0 0
2018 Q2 0 0
2018 Q3 0 0
2018 Q4 0 0
案例 1 的预期结果:将 short 更新为 long
x y z
2018 Q1 NA 0 0
2018 Q2 1 0 0
2018 Q3 1 0 0
2018 Q4 NA 0 0
案例 2 的预期结果:将 long 更新为 short
x y z
2018 Q1 NA 0 0
2018 Q2 1 1 0
2018 Q3 1 1 0
2018 Q4 NA 0 0
案例一
合并非重叠维度,然后子集并分配重叠维度(如:Updating an XTS object)
short2 <- short
for (j in setdiff(colnames(long), colnames(short2))) {
short2 <- merge(short2, long[, j])
}
short3 <- short2
for (j in intersect(colnames(short3), colnames(long))) {
short3[index(long), j] <- long[, j]
}
short3
x y z
2018 Q1 NA 0 0
2018 Q2 1 0 0
2018 Q3 1 0 0
2018 Q4 NA 0 0
案例2
相同的方法:合并非重叠系列维度,然后子集并分配重叠维度
long2 <- long
for (j in setdiff(colnames(short), colnames(long2))) {
long2 <- merge(long2, short[, j])
}
long3 <- long2
for (j in intersect(colnames(short), colnames(long3))) {
long3[index(short), j] <- short[, j]
}
long3
y z x
2018 Q1 0 0 NA
2018 Q2 1 0 1
2018 Q3 1 0 1
2018 Q4 0 0 NA
还有什么比这两个步骤更简单的吗?可能是另一个包中的函数或选项。
【问题讨论】:
-
我想找到一个使用时间序列对象而不是数据框的解决方案
标签: r matrix time-series xts