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

Greg Snow Greg.Snow at imail.org
Fri Aug 27 21:49:56 CEST 2010


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.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Marcus Drescher
> Sent: Friday, August 27, 2010 11:18 AM
> To: r-help at 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 at 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.



More information about the R-help mailing list