r - 使用来自另一个 xts 对象的数据更新 xts 时序对象



我正在寻找一种更简单的方法来使用另一个 xts 对象中的数据更新 xts 时间序列对象。应更新重叠时间段和维度的数据,应添加其他时间段,并根据需要添加缺少的系列维度。目前,我正在使用合并,子集和赋值的组合。有没有办法在更少的步骤中做到这一点?

两个 xts 时间序列对象,一个维度共同 (y) 和两个时间段共同(2018 Q2 和 2018 Q3)。

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 的预期结果:使用long更新short

x  y z
2018 Q1 NA  0 0
2018 Q2  1  0 0
2018 Q3  1  0 0
2018 Q4 NA  0 0

案例 2 的预期结果:使用short更新long

x  y z
2018 Q1 NA  0 0
2018 Q2  1  1 0
2018 Q3  1  1 0
2018 Q4 NA  0 0

案例1

合并非重叠维度,然后对重叠维度进行子集化和分配(如:更新 XTS 对象)

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中无法merge,同时为共享相同名称的列分配优先级。不久前我有一个类似的问题。 默认情况下,R必须生成唯一的列名。之后可以使用setNames直接为列分配公用名,但R将始终分配唯一名称(有关一些说明,请参阅?make.names)。不建议这样做,因为它会使之后的操作变得更加复杂。

操作tsxts对象也很复杂。这是可以做到的,但并不值得花时间。最好转换为data.frametibble并以这些格式开展业务,然后再转换回来。

下面是一个tidyverse解决方案,也使用timetk包。

library(xts)
library(timetk)
library(dplyr)
xts::merge.xts(long, short) %>% #merge xts objects using merge.xts
timetk::tk_tbl() %>% #convert xts object to tibble
dplyr::mutate(y = dplyr::coalesce(y.1, y)) %>% #replace y with coalesced y & y.1
dplyr::select(-y.1) %>% #deselect y.1
timetk::tk_xts(silent = T) #convert back to xts
y z  x
2018 Q1 0 0 NA
2018 Q2 1 0  1
2018 Q3 1 0  1
2018 Q4 0 0 NA

最新更新