如何在 R 中按日期和值合并两个 XTS?

How do I merge two XTS by date and value in R?

所以我想根据日期和值合并两个 XTS。假设其中一个是这样的

a <- c(1,2,3,4)
b <- c(2,4,6,8)
c <- c(3,6,9,12)
x <- xts(cbind(a,b,c),order.by=as.Date(c("2015-01-02","2015-01-05","2015-01-06","2015-01-07")))
x

所以我们得到这个...

           a b  c
2015-01-02 1 2  3
2015-01-05 2 4  6
2015-01-06 3 6  9
2015-01-07 4 8 12

第二个XTS是这样的...

d <- c("b","a","c","b")
e <- c(10,20,10,30)
y <- xts(cbind(d,e),order.by=as.Date(c("2015-01-02","2015-01-05","2015-01-05","2015-01-06")))
y

所以我们得到了这个(最好也去掉引号)...

           d   e   
2015-01-02 "b" "10"
2015-01-05 "a" "20"
2015-01-05 "c" "10"
2015-01-06 "b" "30"

我想得到这个结果...

           d   e     val
2015-01-02 "b" "10"  2
2015-01-05 "a" "20"  2
2015-01-05 "c" "10"  6
2015-01-06 "b" "30"  6

我们可以使用 match 创建一个矩阵 row/column 索引到 x.

的子集
library(zoo)
y$val <- as.character(coredata(x)[cbind(match(index(y), index(x)), 
                                        match(y$d, names(x)))])
y
#            d   e    val
#2015-01-02 "b" "10" "2"
#2015-01-05 "a" "20" "2"
#2015-01-05 "c" "10" "6"
#2015-01-06 "b" "30" "6"