[英]Update an xts time series object with data from another xts object
我正在尋找一種更簡單的方法來使用另一個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所需的結果:在更新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
合並非重疊維度,然后為重疊維度進行子集和分配(如: 更新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
相同方法:合並非重疊系列維度,然后為重疊維度進行子集和分配
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
)。 不建議這樣做,因為它會在更復雜的事情之后采取行動。
操縱ts
和xts
對象也很復雜。 它可以做到,但不值得花時間。 這是最好的轉換為data.frame
或tibble
,做您的企業在這些格式,然后再轉換回來。
以下是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.