1

I have an xts object with multiple columns of the same type. I have another xts object with integers that correspond to column positions in the first object. I would like to generate an third xts object that contains one column representing the value of the column indicated by the corresponding index. For example:

# xts.1:
2003-07-30 17:00:00 0.2015173 0.10159303 0.19244332 0.08138396
2003-08-28 17:00:00 0.1890154 0.06889412 0.12700216 0.04631253
2003-09-29 17:00:00 0.1336947 0.08023267 0.09167604 0.02376319
2003-10-30 16:00:00 0.1713496 0.13324238 0.11427968 0.05946272

# xts.2:
2003-07-30 17:00:00 1
2003-08-28 17:00:00 4
2003-09-29 17:00:00 2
2003-10-30 16:00:00 3

# Desired result:
2003-07-30 17:00:00 0.2015173
2003-08-28 17:00:00 0.04631253
2003-09-29 17:00:00 0.08023267
2003-10-30 16:00:00 0.11427968

I feel like I'm missing something very elementary about how to do this but, if so, it's escaping me at the moment.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
neverfox
  • 6,680
  • 7
  • 31
  • 40

1 Answers1

1

Your data appear to be monthly, so I would strongly recommend you move from a POSIXct index to a Date or yearmon index. Otherwise you may run into issues with timezones and daylight saving time.

One way to solve this problem is to merge xts.1 and xts.2, then loop over all the rows of the resulting object, subsetting the column by the xts.2 column in the merged data.

Since your data are monthly, you can loop over all the observations with apply.monthly.

> xts.3 <- merge(xts.1,xts.2)
> apply.monthly(xts.3, function(x) x[,x$xts.2])
                          [,1]
2003-07-30 17:00:00 0.20151730
2003-08-28 17:00:00 0.04631253
2003-09-29 17:00:00 0.08023267
2003-10-30 16:00:00 0.11427968
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • That's exactly what I ended up doing. Thanks! It feels clunky to do it this way though. You'd think there would be something more elegant and direct. – neverfox Feb 17 '14 at 23:51
  • 1
    @neverfox: there's likely a more elegant solution to your larger problem, but that would require you to back up a few steps before you create the `xts.2` object. – Joshua Ulrich Feb 19 '14 at 00:48