2013-12-11 71 views
2

我需要從xts對象a中提取子集,該子集包含來自另一個xts對象的所有日期,b以及每個日期的相鄰日期集b。相鄰日期可能是b中的每個日期前的n日期和之後的k日期。修改了其他xts對象索引的子集xts對象

例如:

a <- structure(c(9L, 10L, 11L, 15L, 18L, 12L, 13L, 18L, 19L, 19L, 22L, 25L), 
    .Dim = c(12L, 1L), index = structure(c(951696000, 951868800, 951955200, 
    952041600, 952128000, 952214400, 952300800, 952387200, 952473600, 952560000, 
    952646400, 952732800), tzone = "UTC", tclass = "Date"), class = c("xts", "zoo"), 
    .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC") 

b <- structure(1:2, .Dim = c(2L, 1L), index = structure(c(952041600, 952560000), 
    tzone = "UTC", tclass = "Date"), class = c("xts", "zoo"), .indexCLASS = "Date", 
    tclass = "Date", .indexTZ = "UTC", tzone = "UTC") 
n <- 2 
k <- 1 

那麼輸出XTS對象,o,應該是:

o <- structure(c(10L, 11L, 15L, 18L, 18L, 19L, 19L, 22L), .Dim = c(8L, 1L), 
    index = structure(c(951868800, 951955200, 952041600, 952128000, 952387200, 
    952473600, 952560000, 952646400), tzone = "UTC", tclass = "Date"), 
    class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date", 
    .indexTZ = "UTC", tzone = "UTC") 

我得到在b每個日期,然後將2個前日期和1跟隨日期。我知道,例如通過服用:

a[index(b)] 

我在b得到日期。但我無法找到一種方式(可能有效!)來選擇他們旁邊的日期。

回答

1

如果你從字面上的意思是「鄰近的日期」,你可以從index(b)每個元素添加n和減去k

i <- c(0,-seq(n),seq(k)) 
# repeat index(b) for each value we want: 1) actual value, 2) -n, 3) +k 
idx <- rep(index(b), each=length(i)) + i 
o <- a[idx,] 

如果你實際上指的是「鄰國的意見」,你可以採取從a[index(b), which.i=TRUE]輸出,然後添加n並從該向量的每個元素中減去k

i <- c(0,-seq(n),seq(k)) 
b.in.a <- a[index(b), which.i=TRUE] 
# repeat b.in.a for each value we want: 1) actual value, 2) -n, 3) +k 
idx <- rep(b.in.a, each=length(i)) + i 
o <- a[idx,] 

這兩種方法得到相同的R-在你的情況下結果,但如果a不包含連續的日期,它們將會不同。