简体   繁体   中英

Subset xts object with modified index of other xts object

I need to extract a subset from a xts object, a , that contains all the dates from another xts object, b , plus a set of neighboring dates for each of the dates in b . The neighboring dates could be the n dates before each date in b and the k dates after.

For example:

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

then the output xts object, o , should be:

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")

I'm getting each date in b , and then the 2 preceding dates and the 1 following date. I know that for instance by taking:

a[index(b)] 

I get the dates in b . But I couldn't find a way (possibly efficient!) to select the dates next to them.

If you literally meant "neighboring dates", you could add n and subtract k from each element of index(b) :

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,]

If you actually meant "neighboring observations", you could take the output from a[index(b), which.i=TRUE] , and then add n and subtract k from each element of that vector:

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,]

The two approaches yield the same results in your case, but they would be different if a didn't contain contiguous dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM