[R] Iteration within data blocks

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Oct 31 09:41:13 CET 2001


Michaell Taylor <pols1oh at bestweb.net> writes:

> I know there must be an easy way to do this, but I am too new to R and it 
> must be late because I can't seem to get myself around this.  Assume I have,
> 
> scenario 	year	growth	value
> 1		1	.05	1
> 1		2	.03	0
> 1		3	.01	0
> 1		4	0	0
> 2		1	.01	1
> 2		2	.01	0
> 2		3	.01	0
> 2		4	0	0
> 
> What I want to do is within each scenario "grow" the value by the growth rate 
> so that I get :  
> scenario 	year	growth	value
> 1		1	.05	1
> 1		2	.03	1.03
> 1		3	.01	1.0403
> 1		4	0	1.0403
> 2		1	.01	1
> 2		2	.01	1.01
> 2		3	.01	1.0201
> 2		4	0	1.0201
> 
> There are 5,000 scenarios and 10 years. The only thing dancing in my head are 
> giant for loops, which I know isn't right.
> 
> Any suggestions?

Um, first: Are you sure that is what you want (growth values in lines
1 and 5 don't seem to be getting used) and not  1, 1.05, 1.0815,
1.092315 etc.? Assuming that this is the case, I'd try something like

f <- function(x) {
  n <- dim(x)[1]
  g <- c(0,x$growth[-n])
  cbind(x,cumprod(g+1))
}
do.call("rbind",lapply(split(frame,frame$scenario),f))

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list