Search code examples
rmatrixtime-seriesdiagonal

How can I organize time series data onto the diagonal of a data frame ONLY?


If I have a monthly time series like so:

xts <- ts(c(1:48), frequency = 12)


  Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1   1   2   3   4   5   6   7   8   9  10  11  12
2  13  14  15  16  17  18  19  20  21  22  23  24
3  25  26  27  28  29  30  31  32  33  34  35  36
4  37  38  39  40  41  42  43  44  45  46  47  48

How can I organize the values to be on the 'diagonal' only, with zero's everywhere else? As in the below (this format carrying on for all values in xts):

  Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1   1   0  0   0   0   0   0   0   0   0   0   0   
2   0   2  0   0   0   0   0   0   0   0   0   0 
3   0   0  3   0   0   0   0   0   0   0   0   0   
4   0   0  0   4   0   0   0   0   0   0   0   0
5   0   0  0   0   5   0   0   0   0   0   0   0
6   0   0  0   0   0   6   0   0   0   0   0   0   
7   0   0  0   0   0   0   7   0   0   0   0   0   
8   0   0  0   0   0   0   0   8   0   0   0   0
9   0   0  0   0   0   0   0   0   9   0   0   0   
10  0   0  0   0   0   0   0   0   0   10  0   0   
11  0   0  0   0   0   0   0   0   0   0   11  0   
12  0   0  0   0   0   0   0   0   0   0   0  12
13  13  0  0   0   0   0   0   0   0   0   0   0   
14  0   14 0   0   0   0   0   0   0   0   0   0 
15  0   0  15  0   0   0   0   0   0   0   0   0   
16  0   0  0   16  0   0   0   0   0   0   0   0
17  0   0  0   0   17  0   0   0   0   0   0   0
18  0   0  0   0   0   18  0   0   0   0   0   0   
19  0   0  0   0   0   0   19  0   0   0   0   0   
20  0   0  0   0   0   0   0   20  0   0   0   0
21  0   0  0   0   0   0   0   0   21  0   0   0   
22  0   0  0   0   0   0   0   0   0   22  0   0   
23  0   0  0   0   0   0   0   0   0   0   23  0   
24  0   0  0   0   0   0   0   0   0   0   0  24

I'm using a modelling package that demands this format, and have had little luck in finding a solution in packages like 'Matrix' and 'diag', which don't appear set-up to arrange data in this fashion.


Solution

  • Solution by row-binding diag.

    rbind(diag(1:12,12,12), diag(13:24, 12,12), diag(25:36, 12,12 ), diag(37:48,12,12))