[R-SIG-Finance] Offset a vector by 1 to k months

Joshua Ulrich josh.m.ulrich at gmail.com
Sat Jun 25 04:03:14 CEST 2011


On Tue, Jun 21, 2011 at 12:03 AM, Ira Sharenow <irasharenow100 at yahoo.com> wrote:
> I am new to financial time series, zoo, and xts.
>
> I have a length n vector (vDates) of dates. I have an n by k  matrix (mDates). In row i and column j of the matrix, I would like the value to be the row i value of the vector + j months.
>
Adding a certain number of months isn't necessarily that easy.  You
need to choose a calendar convention.  For example, see
RQuantLib::advance().

> mDates[i,j]  = vDates[i] + j months.
>
> I would like to do this without loops.
>
> I solved the problem with just numbers.
>
> v1 = 11:15
> m1 = matrix(rep(0,20), nrow = 5)
> m1 = v1 + col(m1)
>
> I do not know how to add months in zoo or xts, so I tried lubridate.
>
> library(lubridate)
> vDate = as.Date(c("2011-06-01", "2011-06-02", "2011-06-03"), "%Y-%m-%d")
> mDate2  = vDate  + months(1)  this works fine
>
Are you sure this is fine?  Are you comfortable with the assumptions
being made?  For example:
mDate <- timeBasedSeq("201101/20110203")
tail(mDate + months(1))
# [1] "2011-03-01" "2011-03-02" "2011-03-03" "2011-03-01"
# [5] "2011-03-02" "2011-03-03"

> But I do not know how to solve the problem for a matrix.
>
> library(xts)
> charvec = paste("2011-0", 1:2, "-01", sep = "")
> theData = matrix(rep(0,6),nrow = 2)
> z1 = xts(theData, as.Date(charvec))
>
> I want the rows of z1 data to be
> 2011-02-01  2011-03-01 2011-04-01
> 2011-03-01  2011-04-01 2011-05-01
>
You can add a month to each index value via:
ISOdate(year(index(z1)),month(index(z1))+1,day(index(z1)))
# [1] "2011-02-01 12:00:00 GMT" "2011-03-01 12:00:00 GMT"

But you can't have Date class objects inside xts/zoo objects.  xts/zoo
objects are just matrix objects with an index attribute and matrix
objects can only contain atomic types (or list or expression).

Perhaps if you provide a bit more detail about your actual problem,
someone can show you a more "R-like" solution.

> Thanks.
> Ira
>

Hope that helps,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com



More information about the R-SIG-Finance mailing list