0

So I have been trouble with creating a counter, hopefully you all will be able to help. Lets say I have a vector

x <- c(40,10,60)

The desired output would be a new matrix 3 x n each row being a new date looking something like this..

40 39 38 37 36 35 34 33 32 31 30...
10 9 8 7 6 5 4 3 2 1 0 0 0 
60 59 58 57 56 55 54 53 52 51 50  

What I want is for the row to subtract one from the previous entry an n number of times. How would I go about doing this?

Any help is much appreciated.

Adam Warner
  • 1,334
  • 2
  • 14
  • 30

1 Answers1

2
> n = 12 # or whatever you want

> t(sapply(c(40,10,60), function(x) pmax(seq(x, (x-n+1), -1), 0) ))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
[1,]   40   39   38   37   36   35   34   33   32    31    30    29    28
[2,]   10    9    8    7    6    5    4    3    2     1     0     0     0
[3,]   60   59   58   57   56   55   54   53   52    51    50    49    48
smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    This is exactly what I was looking for. Very concise, thank you for the quick answer. – Adam Warner Jul 10 '15 at 19:57
  • Welcome! Learn to love the `*apply` family. – smci Jul 10 '15 at 19:58
  • 1
    Yeah I knew the answer was going to be in the *apply function, but the seq stuff would have gone right over me. – Adam Warner Jul 10 '15 at 20:01
  • Sure. Have a look at the documentation for `seq` and its variants `seq_along, seq_len`. Together they can generate any (arithmetic) sequence you might want. Then by scaling and multiplying, you can get any numeric sequence. – smci Jul 10 '15 at 20:02
  • I think you can also do `matrix(pmax(x- rep(sequence(n+1)-1,each=length(x)),0),nrow=3)` – akrun Jul 10 '15 at 20:07
  • @akrun can you fix that syntax, and post as an answer? If so, you win the golf. – smci Jul 10 '15 at 20:12
  • Here `x <- c(40, 10, 60)`. and `nrow=length(x))`. I am getting the same result as yours. But, it is basically your solution. So, I better leave it here :-) – akrun Jul 10 '15 at 20:14