[R] How to calc ratios base on current and previous row?

2010-08-27 Thread Marcus Drescher
Hi all, I want to calculate in each row a ratio based on number in the current row and the previous row. Is there a way to do this without for-loops because that is extremely slow. A B [1] 2 2 [2] 2 3 [3] 4 5,5 ... B2 = A2 +

Re: [R] How to calc ratios base on current and previous row?

2010-08-27 Thread Bert Gunter
Your question is unclear. If the calculation of B[3] now depends on the newly calculated value of B[2], then the answer is no: you must loop. If B[3] is based on the original B[2] value, then the answer is yes, and the solution is just a matter of simple indexing, which I leave as an exercise. --

Re: [R] How to calc ratios base on current and previous row?

2010-08-27 Thread Ted Harding
On 27-Aug-10 17:17:50, Marcus Drescher wrote: Hi all, I want to calculate in each row a ratio based on number in the current row and the previous row. Is there a way to do this without for-loops because that is extremely slow. A B [1] 2 2 [2] 2 3

Re: [R] How to calc ratios base on current and previous row?

2010-08-27 Thread Joshua Wiley
Hi Marcus, I am guessing you are thinking in terms of Excel, where in column B, you could enter the formula =(A2 + 0.5*B1) and just drag it down however many cells you wanted. In R, it would be expressed a bit differently. If k indexes your rows, I believe you want: B[k] = A[k] + 0.5 * B[k -

Re: [R] How to calc ratios base on current and previous row?

2010-08-27 Thread Greg Snow
For this particular case there is a nice shortcut (there is still looping , but it is internal and quick): a - c(2,2,4, sample(1:10, 97, TRUE) ) b - cumsum( (1/2)^(99:0)*a )/( (1/2)^(99:0) ) ## compare bb - numeric(100) bb[1] - a[1] for( i in 2:100 ) { bb[i] - 1/2 * bb[i-1] + a[i] }