Exercise

Math with non-overlapping indexes

The previous exercise illustrated the ins and outs of doing basic math with xts objects. At this point you are aware that xts respects time and will only return the intersection of times when doing various mathematical operations.

We alluded to another way to handle this behavior in the last exercise. Namely, re-indexing your data before an operation. This makes it possible to preserve the dimensions of your data by leveraging the same mechanism that xts uses internally in its own Ops method (the code dispatched when you call + or similar).

The third way involves modifying the two series you want by assuring you have some union of dates - the dates you require in your final output. To do this you will need a few functions that won't be dealt with in depth until Chapter 3, but are very useful here.

merge(b, index(a))

Don't worry if you aren't yet familiar with merge(). This exercise may be easier if you just follow along with the instructions.

Instructions

100 XP
  • Using a and b from the previous exercise, get the value of a + b for each date in a. If no b is available on a given date, the answer should be a on that date.
  • Now add a to b, but this time make sure all values of a are added to the last known value of b in time.