Hello,
 
I'd do:
ave(testvec, FUN=cumsum)+1

But in R everything can be done in a trillion different ways. ;-)

Cheers!!
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


>________________________________
>From: "ONKELINX, Thierry" <thierry.onkel...@inbo.be>
>To: Chris82 <rubenba...@gmx.de>; "r-help@r-project.org" <r-help@r-project.org>
>Sent: Wednesday, October 5, 2011 11:54 AM
>Subject: Re: [R] optimize R code: replace for loop
>
>You can vectorize it using cumsum.
>
>cumsum(c(1, testvec))
>
>all.equal(final.sum, cumsum(c(1, testvec)))
>
>> -----Oorspronkelijk bericht-----
>> Van: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org]
>> Namens Chris82
>> Verzonden: woensdag 5 oktober 2011 11:50
>> Aan: r-help@r-project.org
>> Onderwerp: [R] optimize R code: replace for loop
>> 
>> Dear R Users,
>> 
>> at the moment I am trying to optimize an R script.
>> 
>> testvec <- c(0,1,0,1,1,1,1,0,0,1,0,1,0)
>> 
>> 
>> sum.testvec <- vector()
>> tempsum <- 1
>> for (e in 1:length(testvec)){
>> sum.testvec[e] <- tempsum+testvec[e]
>> tempsum <- sum.testvec[e]
>> 
>> }
>> 
>> final.sum <- c(1,sum.testvec)
>> 
>> 
>> Is there an option to do something with apply? Unfortunately I am not so
>> familiar with the apply functions.
>> 
>> Thanks.
>> 
>> --
>> View this message in context: http://r.789695.n4.nabble.com/optimize-R-code-
>> replace-for-loop-tp3873945p3873945.html
>> Sent from the R help mailing list archive at Nabble.com.
>> 
>> ______________________________________________
>> 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.
>
>
>
        [[alternative HTML version deleted]]

______________________________________________
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