# [R] Formula that includes previous row values

Pele drdionc at yahoo.com
Mon Feb 23 22:48:01 CET 2009

```Hi Jorge - many thanks for you suggestion, but I am looking for a way where I
don't have to use a loop.  I meant to include that in my description.

Thanks again!

Jorge Ivan Velez wrote:
>
> Dear Pele,
> Probably not the best way to proceed but it works:
>
> 1.00    1.00
> 2.00    0.00
> 3.00    1.00
> 4.00    3058
> 5.00    0.00
> closeAllConnections()
> X
>
> x3<-0
> for(i in 2:(nrow(X)+1)) x3<-c(x3, X\$X2[i-1]+0.24*x3[i-1])
> X\$x3<-x3[-1]
> X
>
> HTH,
>
> Jorge
>
>
> On Mon, Feb 23, 2009 at 3:59 PM, Pele <drdionc at yahoo.com> wrote:
>
>>
>> Hi R users,
>>
>> Is there an easy way in R to generate the results table below using table
>> 1
>> and the formula (simplified version of the real problem)?  It would be
>> easy
>> if I knew the R equivalent of SAS's retain function, but could not find
>> one.
>>
>> Thanks in Advance for any help!
>>
>> table1:
>>
>> ID      X2         X3
>> 1.00    1.00       0
>> 2.00    0.00
>> 3.00    1.00
>> 4.00    3058
>> 5.00    0.00
>> 6.00    6.00
>>
>> Formula: X3 = x2 + (.24 * x3)
>>
>> where the values in the x3 column of the result table are retained from
>> previous x3 rows.. Also the first x3 value is initialized to 0 to start
>>
>> e.g.
>>        for ID=1 we have  1 + .24(0)                    = 1.00
>>        for ID=2 we have  0 + .24(1)                    = 0.24
>>        for ID=3 we have  1 + .24(.24)          = 1.06
>>        for ID=4 we have  3058 + .24(1.06)      = 3058.25
>>        etc.............
>>
>> Results:
>> ID      X2      x3
>> 1.00    1.00    1.00
>> 2.00    0.00    0.24
>> 3.00    1.00    1.06
>> 4.00    3058    3058.25
>> 5.00    0.00    733.98
>> 6.00    6.00    182.16
>> --
>> View this message in context:
>> http://www.nabble.com/Formula-that-includes-previous-row-values-tp22170010p22170010.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help