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]
}

all.equal( b, bb )

you will get some slight differences due to rounding error from the 2 methods.

this can be generalized to some degree, but if things get too complicated then 
you may need to loop.

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.s...@imail.org
801.408.8111


> -----Original Message-----
> From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-
> project.org] On Behalf Of Marcus Drescher
> Sent: Friday, August 27, 2010 11:18 AM
> To: r-help@r-project.org
> Subject: [R] How to calc ratios base on current and previous row?
> 
> 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
> 
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to