[R] How to calc ratios base on current and previous row?
(Ted Harding)
Ted.Harding at manchester.ac.uk
Fri Aug 27 19:34:29 CEST 2010
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
> [3] 4 5,5
> ...
>
> B2 = A2 + 0.5*B1
>
> Thanks in advance.
> Best
> Marcus
If n is the total number of rows, then :
B[(2:n)] <- A[(2:n)] + 0.5*B[1:(n-1)]
should work! This assumes that A and B have been extracted as vectors,
or can be referred to separately as in a dataframe (say D), like
D$B[(2:n)] <- D$A[(2:n)] + 0.5*D$B[1:(n-1)]
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 27-Aug-10 Time: 18:34:27
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list