Reducing multi-column xts to single column xts based on provided column indexes

StackOverflow https://stackoverflow.com/questions/21829617

  •  12-10-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top