2

I have a single column matrix (the result of an rbind operation) of initial starting values named 'starts' for several timeseries which begin at different months and appears as follows:

starts <- matrix(rep(100,5),ncol=1)
rownames(starts) <- month.name[1:5]
starts          
          [,1]
January   100
February  100
March     100
April     100
May       100

Clearly in reality the starting numbers are not always 100.

My goal is to combine this with a separate table() that contains the diminishing amounts by which 'starts' decreases monthly.

mytable <- structure(c(20L, 0L, 0L, 0L, 0L, 10L, 10L, 0L, 0L, 0L, 5L, 10L, 
5L, 0L, 0L, 5L, 10L, 5L, 10L, 0L), .Dim = c(5L, 4L), .Dimnames = list(
    c("1", "2", "3", "4", "5"), c("1", "2", "3", "4")), class = "table")
mytable

    1    2   3   4
1  20   10   5    5
2   0   10  10   10
3   0    0   5    5
4   0    0   0   10
5   0    0   0    0

The periods here: 1,2,3,4 refer to the periods between months, so period 1 shows how much a time series value decreases between January and February. The vertical numbers 1,2,3,4,5 correspond to the time series.

The output should be a new table that looks like the following:

         January  February  March  April   May
January    100       80      70      65     60
February            100      90      80     70
March                       100      95     90
April                               100     90
May                                        100

I thought I might be able to do this with a function in the manner of sweep, such as:

result <- sweep(starts,2,mytable,"-")

However, clearly sweep does not work on tables in the nature of a correlation matrix, such as the above.

Many thanks in advance for any help.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
RichS
  • 659
  • 12
  • 19

1 Answers1

4

Not sure if this is ideal, but here's an attempt:

starts[,rep(1,5)] - cbind(0, t(apply(mytable, 1, cumsum)) )

#         [,1] [,2] [,3] [,4] [,5]
#January   100   80   70   65   60
#February  100  100   90   80   70
#March     100  100  100   95   90
#April     100  100  100  100   90
#May       100  100  100  100  100
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Just a reminder: one can always cut the lower triangle from the result: `result[lower.tri(result)] <- NA` – bergant Nov 10 '15 at 00:48